问题描述
在基于HotTowel的项目中,我使用Durandal 1.1.1进行路由.
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.
我的路由配置如下:
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'
}
如果用户要转到#/moduledetail/1
并且尚未通过身份验证,我想让浏览器导航到路由#/login/moduledetail/1
,因此在成功登录后路由回到#/moduledetail/1
.
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
.
可能的解决方案是将navigateTo
放在moduledetail
的canActivate
中,例如:
A possible solution is to put a navigateTo
in canActivate
of moduledetail
like:
function canActivate()
{
if (!loggedIn)
router.navigateTo(`#/login/moduledetail/1`)
return false;
}
但是在canActivate
期间导航到另一个页面似乎很愚蠢.
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?
推荐答案
在Durandal 2.0中,这是使用router.guardRoute实现的:
In Durandal 2.0, this is achieved using router.guardRoute:
auth = require('auth');
router.guardRoute = function(model, route) {
return auth.loggedIn() || '#/login';
};
从我阅读的内容来看,尽管未记录下来,但该行为在Durandal 1.x中是相同的.保护路由是在加载viewModel之后但在视图模型上调用Activate之前调用的函数.如果为true,则继续进行路由.如果是字符串,路由器将尝试导航到与该字符串关联的路由.
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.
这篇关于Durandal中的条件路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!