Can ngRoute use a QueryString parameter instead of the hash? - angularjs

The ASP MVC app I am working on uses forms authentication with a timeout. This means that when the session has timed out and the user clicks refresh they get redirected to a login page, and after that they get directed back to the original page without the deep-linked client-side # part of the url.
Is there a way to get ngRoute to base its deep-linked client-side url on a querystring instead? For example
http://somesite.com/?p=/home

The first thing to do is to have the ASP MVC server side capture any URLs that should related to your client-side angular routing and return the single-page app HTML. When registering your ASP MVC routes add the following rule
routes.MapRoute(
name: "Angular",
url: "x/{*clientPath}",
Where the "x/" is the base part of your client app, of course you can do without the "x" in the URL if your entire app is a single-page angular app, in which case you will need to add a preceding rule to render your ASP MVC server side account-login page.
Then in your Angular app make sure you use Html5 mode, like so
app.config(["$locationProvider", "$routeProvider", function ($locationProvider, $routeProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false,
rewriteLinks: true
});
$routeProvider.when("/x/docs/upload", {
......
});
$routeProvider.when("/x/docs/view", {
......
});
$routeProvider.otherwise({
redirectTo: "/x/docs/upload"
});
}]);
When you open your browser and navigate to http://mysite/x/what/ever/you/like the server side will use XController.Index to render Views\x\Index.cshtml, which will load your single page app, and then ngRoute will take over and present the relevant view for the "x/what/ever/you/like" part.

Related

Routing in SPA with ASP.NET MVC 6 and 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
});
}
}

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'})
});

what is the best way to get data from nodejs server and send data to angular generated page?

I am new to nodejs+angular app. I just want to pass some data from node server to pages generated by angular. How can I do that? is there something like,
response.render('URL',JSONDATA);
using which I am able to get data to a specified URL. Just for information I am using ng-view/ ng-route on my UI pages for fast loading.
On Client side:
app.config([ '$locationProvider','$routeProvider', function($locationProvider,$routeProvider) {
//$locationProvider.html5Mode(true);
$routeProvider.when('/', {
templateUrl : 'src/pages/login.html'
}).when('/new-enquiry', {
templateUrl : 'src/pages/enq-form.html'
}).when('/dashboard', {
templateUrl : 'src/pages/dashboard.html'
}).when('/edit-enquiry', {
templateUrl : 'src/pages/edit.html'
}).when('/all-enquiry', {
templateUrl : 'src/pages/all-enquiry.html'
});
} ]);
What I have to do is for example in login page, after submitting I need to redirect to a new page and send username to that page. I dont want to use ejs and jade.
Have a look at the docs at
https://docs.angularjs.org/api/ngRoute/provider/$routeProvider
https://docs.angularjs.org/api/ng/service/$http
For example, you can configure a controller for every route, which then uses the $http service to request data from your Node.js backend. The data is rendered in the template you provide per route (such as src/pages/login.html).

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')

AngularJS Route breaks on manual refresh

In the config method, I have some routes defined as follows:
$locationProvider.html5Mode(true);
$routeProvider.when('/', {
...
});
$routeProvider.when('/front', {
...
});
$routeProvider.when('/user/account', {
...
});
Everything works fine when navigating through the app using <a href=""> tags. However, when I go to /user/account and manually refresh my browser, it pops the /account off the route and redirects me to /user, breaking the rendering in the process since there is no route defined for /user.
I noticed this does not happen when I configure the route to be /account only, but this is not fixing the real issue. So I set up the following catch-all (below the routes above) to log what's happening:
$routeProvider.otherwise({
redirectTo: function() {
console.log('bumped', arguments);
return '/';
}
});
and saw it was trying to match /account instead of /user/account. What is going on here?
I am on Angular 1.1.5. The server returns index.html appropriately on all requests (for HTML5 mode), so it seems like a client-side issue.
How can I configure this route correctly?
EDIT
Turns out this is a bug in 1.1.5 core.
https://github.com/angular/angular.js/issues/2799
patched here
https://github.com/IgorMinar/angular.js/commit/2bc62ce98f893377bfd76ae211c8af027bb74c1d
Ended up using ui-router which solved this issue.

Resources