【发布时间】:2018-02-13 23:11:48
【问题描述】:
我有一个带有延迟加载模块的 Angular 4.3.6 应用程序。这是一个部分根路由器:
const routes: Routes = [
{ path: '', redirectTo: 'fleet', pathMatch: 'full' },
{
path: '',
component: AppComponent,
canActivate: [AuthenticationGuard],
children: [
{
path: 'fleet',
loadChildren: "./modules/fleet.module",
canActivate: [AuthenticationGuard]
},
{
path: 'password/set',
loadChildren: "./modules/chooseNewPassword.module",
canActivate: [ChoosePasswordGuard]
}
]
}
]
// Exports RouterModule.forRoot(routes, { enableTracing: true });
我在这两个示例模块中的子路由器:
舰队:
RouterModule.forChild([
{
path: '',
component: FleetComponent,
canActivate: [AuthenticationGuard]
}
]);
选择新密码:
RouterModule.forChild([
{
path: '',
component: ChooseNewPasswordComponent,
canActivate: [ChoosePasswordGuard]
}
]);
AuthenticationGuard 调用的方法如下所示:
return this.getUserSession().map((userSession: UserSession) => {
if (userSession && userSession.ok) {
return true;
}
else if (userSession && userSession.expired) {
this.router.navigate(['password/set'])
.catch((e: Error) => console.error(e));
return true;
}
else {
window.location.replace('/');
return false;
}
}
所以,如果用户的会话正常,它就会激活路由。如果用户的密码过期,它会将用户重定向到选择新密码模块。如果没有会话,则重定向到登录。
ChoosePasswordGuard 做了类似的事情,但只保护选择新密码组件(通常使用不同的工具设置密码):
return this.getUserSession().map((userSession: UserSession) => {
if (userSession) {
return userSession.expired;
}
else {
return false;
}
});
这在模块拆分之前有效。
现在,我陷入了重定向循环。在路由器跟踪打开的情况下,我观察到以下顺序。用户登录,AuthenticationGuard 更正重定向到 /password/set 模块,并移交给ChooseNewPasswordGuard:
- NavigationStart(id: 4, url: '/password/set')
- RoutesRecognized {id: 4, url: "/password/set", urlAfterRedirects: "/password/set", state: RouterStateSnapshot}
- GuardsCheckStart {id: 4, url: "/password/set", urlAfterRedirects: UrlTree, state: RouterStateSnapshot}
- GuardsCheckEnd {id: 4, url: "/password/set", urlAfterRedirects: UrlTree, state: RouterStateSnapshot, shouldActivate: true}
- NavigationCancel {id: 4, url: "/password/set", 原因: ""}
然后这个循环会重复。
(如果我将整个 ChooseNewPasswordGuard 替换为 return Observable.of(true);,它也会重复)
编辑:即使我在 URL 栏中提供 /#/password/set,我也会被重定向到根页面 (/)...
问题:
既然模块是延迟加载的,我在路由器或守卫中做错了什么以强制执行此循环?我对
shouldActivate: true后跟NavigationCancel reason: ""感到特别困惑。这是否与我直接在 AuthenticationGuard 中重定向这一事实有关,现在这个保护应用于我的主要空根路由 (
{ path: '', redirectTo: 'fleet', pathMatch: 'full' }) 它总是被调用并重定向,甚至一旦我设置了路径?我真的需要在子路由和根路由中重复
canActivate守卫吗?像往常一样,欢迎任何其他 cmets。
【问题讨论】:
标签: angular lazy-loading angular-router angular-router-guards