Routing in SPA with ASP.NET MVC 6 and AngularJS - angularjs

I have a sample MVC6 single page app with one view in which I want to load 2 Angular partials using ngRoute. You can have a look at it at GitHub
There are 3 URLs in the app:
localhost - Index.cshtml
localhost/games - Index.cshtml with Angular's gamelist.html partial
localhost/games/2 - Index.cshtml with Angular's game.html partial
The routes config is the following:
MVC:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}");
routes.MapRoute("gamelist", "games", new { controller = "Home", action = "Index"});
routes.MapRoute("gameWithId", "games/2", new { controller = "Home", action = "Index" });
});
Angular:
myApp.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/games', {
templateUrl: 'partials/gameslist.html',
controller: 'GameController',
controllerAs: 'ctrl'
})
.when('/games/:gameId', {
templateUrl: 'partials/game.html',
controller: 'GameController',
controllerAs: 'ctrl'
});
$locationProvider.html5Mode(true);
}]);
It all works perfectly fine as long as I start the app from the home page '/' and then navigate to the partials using the links on the page. The problem is that the URL #3 (localhost/games/2) does not work if I start the app from it, by typing it in the address bar. The URL #2 (/games/) does work.
The reason why #3 does not work is that MVC removes '/games' part from the URL and what Angular gets is just '/2'. If you run the sample app, you will see that '$location.path = /2'. Of course Angular cannot map using that path and no partial is rendered. So my question is - how to make MVC return the full path to the client so that Angular can map it?

You can get it to work with HTML5 mode, you just need to ensure that every request maps back to your Index.cshtml view. At that point the AngularJS framework loads, client-side routing kicks in and evaluates the request URI and loads the appropriate controller and view.
We've done this with multiple Angular apps inside MVC with different .cshtml pages, though we use attribute routing with the wildcard character, e.g.
[Route("{*anything}")]
public ActionResult Index()
{
return View("Index");
}
The wildcard operator (*) tells the routing engine that the rest of the URI should be matched to the anything parameter.
I haven't had chance to get to grips with MVC6 yet but I think you can do something like this with the "new" version of attribute routing?
[HttpGet("{*anything:regex(^(.*)?$)}"]
public ActionResult Index()
{
return View("Index");
}

To make link #3 work from the browser's address bar, I turned off "html5Mode" in Angular and made links #-based.

kudos to this blog
I think it is a better solution.
His solution is rewriting the request that doesn't fit to any route and doesn't have any extension to the landing page of angular.
Here is the code.
public class Startup
{
public void Configure(IApplicationBuilder app, IApplicationEnvironment environment)
{
// Route all unknown requests to app root
app.Use(async (context, next) =>
{
await next();
// If there's no available file and the request doesn't contain an extension, we're probably trying to access a page.
// Rewrite request to use app root
if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/app/index.html"; // Put your Angular root page here
await next();
}
});
// Serve wwwroot as root
app.UseFileServer();
// Serve /node_modules as a separate root (for packages that use other npm modules client side)
app.UseFileServer(new FileServerOptions()
{
// Set root of file server
FileProvider = new PhysicalFileProvider(Path.Combine(environment.ApplicationBasePath, "node_modules")),
// Only react to requests that match this path
RequestPath = "/node_modules",
// Don't expose file system
EnableDirectoryBrowsing = false
});
}
}

Related

Angular/Express Redirect Initial Route (localhost:3000)

Simple question.
I'm building an Express web application with two views/routes (controlled by Angular):
localhost:3000/#/join
localhost:3000/#/find
I want the initial "localhost:3000" to forward to "localhost:3000/#/join", but currently, the page only loads the generic static content and does not include the unique html partial content associated with the view.
I'm using the following code.
require('./app/routes.js')(app);
app.all('*', function(req, res){
res.redirect('/#/join');
});
The forwarding works correctly for all url (e.g. localhost:3000/blah, localhost:3000/blah2, etc.) -- except for the initial localhost:3000.
Any suggestions?
Figured out the answer. I just need to include an "otherwise" statement at the end of my Angular routeProvider.
var app = angular.module('meanMapApp', ['addCtrl', 'queryCtrl','ngRoute'])
.config(function($routeProvider){
$routeProvider.when('/join', {
controller: 'addCtrl',
templateUrl: 'partials/addForm.html',
}).when('/find', {
controller: 'queryCtrl',
templateUrl: 'partials/queryForm.html',
}).otherwise({redirectTo:'/join'})
});

Dynamic route request render not working, backend express

I want to try dynamic route request but It's not working properly. And here I explain my coding style step by step.
<nav class="main-nav" ng-show="global.user.user_type!='admin'" ng-repeat="mMenu in Mainmenu">
{{mMenu.MenuName}}
</nav>
This code contain URL link and It's load every time with a variable that is web address link. And the link is something like that - http://localhost/views/adminpanel/about.html
In AngularJS Controller contain the code -
$scope.geturl = function(url)
{
var params = {
url1 : '/views/adminpanel/'+url
}
$http({'method' : 'post', url : 'views/adminpanel/'+url, data: params
}).success(function(data)
{
}).
error(function(data){
})
}
configuring and using ngRoute -
when('/views/adminpanel/:url', {
controller: 'homeCntrl',
templateUrl: 'views/adminpanel/:url'
})
In server side (Express) :
Routing HTTP requests, Configuring middleware and Rendering HTML views
app.post('/views/adminpanel/:url',auth.requiresLogin, users.geturl);
exports.geturl= function(req,res)
{
var url = req.body.url1;
res.render(url);
}
This is all about my rendering process but It's not working. In browser It only shows the URL link but not shows any content. How can I solve It any idea?
I think you are confusing things:
first of all you have a link together with a ngClick: you should have either of those
your ngClick has an empty success function, so it does nothing with the template
you have a route set with express that matches with the ngRoute (btw, POST is usually used to create resources, you should GET the template)
your templateUrl is going to send a GET request to (literally) /views/adminpanel/:url, it does not replace :url
To fix it:
set a different endpoint for your APIs
use a GET endpoint instead of a POST
change the ngRoute to:
when('/views/adminpanel/:url', {
controller: 'homeCntrl',
templateUrl: function(param) {
return '/api/<path>/' + param.url;
}
})
remove the ngClick from the <a>

send parameter along url angularjs

I am working on project where my role is server-side programmer.Client side developer used Angular js while designing pages.
Problem I am facing is we have one page where I need to pass one parameter along with url to server
<a id="startQuiz" href="#/Quiz" >Start Quiz</a>
jquery code is
$('#startQuiz').click(function (e) {
e.preventDefault();
window.location.href = '#/Quiz/' + selectedTopic;
}
Controller code is
#RequestMapping(value="/Quiz", method = RequestMethod.GET)
public String Quiz(HttpServletRequest request,Model model,HttpServletResponse response,#RequestParam(value = "topic", required = false) String topic) throws Exception {
System.out.println("select topic : "+topic);
}
I am getting topic as null cause Nothing after the hash # sign is getting sent to the server, hence the null values
Rounting file Is
app.config(function($routeProvider){
$routeProvider
.when("/Quiz", {templateUrl: "Quiz", controller: "PageCtrl"})
});
So, What change should I make in routing so I can get value of topic in Controller
Any way to do that?
The URL of the page is not what matters here. That URL will only load the main page template.
What matters is the URL used to send the AJAX request to your backend controller.
The route should be defined as
$routeProvider
.when("/Quiz/:topicId", {
templateUrl: "Quiz",
controller: "PageCtrl"
})
Then, using the $routeParams service in the PageCtrl, you can get the value of topicId, and send the appropriate AJAX request to the backend.

AngularJS frontend (with routing) combined with a Laravel API as the backend

So I've been trying to find a solution for my problem during the last 7 days or so. I have almost given up on this so this is my last attempt at solving this.
I'm trying to build a recipe site which fetches the recipes from my Laravel API Backend (i.e. api/recipes returns all recipes in the MySQL-database). The data is requested from the AngularJS frontend via the $http-service, so far so good.
Single page applications like this isn't a problem since I've defined the routes in Laravel like this. All HTTP reqs who isn't sent to the RESTful API is redirect to my index-view where I want AngularJS to take over the routing from there on.
Route::get('/', function()
{
return View::make('index');
});
Route::group(array('prefix' => 'api'), function() {
Route::resource('recipes', 'RecipeController',
array('except' => array('create', 'edit', 'update')));
Route::resource('ingredients', 'IngredientController',
array('except' => array('create', 'edit', 'update')));
Route::resource('nutrients', 'NutrientController',
array('except' => array('create', 'edit', 'update')));
Route::resource('IngredientsByRecipe', 'IngredientsByRecipeController');
});
App::missing(function($exception)
{
return View::make('index');
});
I want the user to be able to edit existing recipes, create new ones etc. Therefore I've created these routes in Angular:
var recipeApp = angular.module('recipeApp', [
'ngRoute',
]);
recipeApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'list.html',
controller: 'MainCtrl'
})
.when('/edit/:recipeId', {
templateUrl: 'detail.html',
controller: 'EditCtrl'
})
.when('/new', {
templateUrl: 'detail.html',
controller: 'CreateCtrl'
})
.otherwise({
redirectTo: '/'
});
}
]);
Unfortunately I can't seem to get this to work even with this routing in Angular. I've seen similar problems being solved by decoupling the app and stuff like that, and I've tried something like that by running my Angular frontend at port 8888 and the Laravel backend at port 8000 but then I got a problem with CORS.
I'm eager to get this to work but can't seem to figure out how to get it to work. It seems like the browser ignores the Angular routing and only uses the Laravel routing, which means that I can only access the index view or the API. How should I solve this?
Building hybrid apps like this is something I would not recommend. You should separate your Laravel API backend from your AngularJS frontend. You can then set up services in AngularJS to call your API. API driven development is the way to go.
If you have problems with CORS, you can modify the headers in your Laravel responses to fix this. To fix the problem with every Laravel route, you can add the following somewhere at the top of your routes.php file:
header('Access-Control-Allow-Origin: *');
Or (better solution if you want it for all routes), add this to your after filter in filters.php:
$response->headers->set('Access-Control-Allow-Origin', '*');
Or you can set up a separate filter:
Route::filter('allowOrigin', function($route, $request, $response) {
$response->header('Access-Control-Allow-Origin', '*');
});
Now, to answer your question ...
In the head of your index file (for Angular), add <base href="/">, and also add $locationProvider.html5Mode(true); inside your Angular config; you can just place it after your $routeProvider.when('/', { ... }); function.

Routing issue b/w angularjs and expressjs

Express.js routing of /question/ask
app.get('/question/ask', function (req, res){
console.log('index.js');
console.log('came to question/:id');
res.render('app');
});
The corresponding angularjs routing is:-
when('/ask', {
templateUrl: 'partials/askQuestion',
controller: 'xController'
}).
whereas it should be:-
when('/question/ask', {
templateUrl: 'partials/askQuestion',
controller: 'xController'
}).
I'm working in $locationProvider.html5Mode(true); mode.
Is there anyway i can get the later angularjs routing working. I'm using angularjs 1.1.5 version.
Edit:-
app.get('/*', function (req, res){
console.log('index.js');
console.log('came to question/:id');
res.render('app');
});
has the same problem, the angular route only routes the last /ask for /question/ask.
The issue for me is that I can only do 1 of the following :-
www.example.com/question/:qId
www.example.com/discussion/:aId
because the application will catch only 1 when('/:id', { as it does not include the previous /question/ or /discussion/
Well, if you have the same routes on Express and Angular, if the user types the url directly in the browser you will hit the Express route, but if the user is navigating within the application, then he will hit the Angular route.
Is this what you want ?
What some do is to have a different set of routes on the server for the REST API, and a catch all route to serve the application no matter what the user type as a URL, bringing the user to the home page when a server route is hit. Within the application of course navigation is handled by Angular routes. The problem is that you get no deep linking.
Some other apps have the same routes on both the server and the client, this way they can serve some contents no matter what.
Some will write involved route rewriting to make sure that you both get the application bootstrapping code AND the required URL, thus allowing deep linking.
Cheers
using angular version 1.2.0-rc.3 cures the problem.
change:
var myApp = angular.module('myApp', []);
to
var myApp = angular.module('myApp', ['ngRoute']);
And include:-
script(type='text/javascript', src='js/angular-route.js')

Resources