Conditional routing in Durandal

我与影子孤独终老i 提交于 2019-12-07 18:48:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!