问题
In my HotTowel based project, I'm using Durandal 1.1.1 for routing.
I have a login route, which I want to activate if the user is not logged in.
my route config is like:
var routes = [ {
url: 'login',
moduleId: 'viewmodels/login',
name: 'Login',
visible: true,
caption: 'Login'
},{
url: 'moduledetail/:id',
moduleId: 'viewmodels/moduledetail',
name: 'ModuleDetail',
visible: true,
caption: 'ModuleDetail'
}
I want if user want to go #/moduledetail/1
and is not authenticated yet, the browser navigate to route #/login/moduledetail/1
so after successful login route back to the #/moduledetail/1
.
A possible solution is to put a navigateTo
in canActivate
of moduledetail
like:
function canActivate()
{
if (!loggedIn)
router.navigateTo(`#/login/moduledetail/1`)
return false;
}
But navigating to another page during canActivate
seems so foolish.
Is there any method to tell Durandal that while routing, on this condition use this route?
回答1:
In Durandal 2.0, this is achieved using router.guardRoute:
auth = require('auth');
router.guardRoute = function(model, route) {
return auth.loggedIn() || '#/login';
};
From what I've read, though undocumented the behavior works the same in Durandal 1.x. Guard route is a function called after the viewModel is loaded but before activate is called on the view model. If true, routing proceeds. If a string, the router tries to navigate to the route associated with that string.
来源:https://stackoverflow.com/questions/19119544/conditional-routing-in-durandal