我的主应用程序路由器中有以下内容:
{ path: 'users', loadChildren: 'app/modules/users/users.module#UsersModule', canLoad: [AuthGuard] }
当用户转到http://localhost:4200/用户/1234 http://localhost:4200/users/1234为了查看他们的个人资料,我尝试保存完整的网址(包括上面的用户 ID),以便在他们登录后我可以路由回该页面。
问题是,Route
中的参数canLoad
函数只有一个path
不包含上面的用户 ID 的字段,仅包含路径users
。有什么方法可以实现这个目标吗?
第一条评论后编辑
用户路由模块确实有一个canActivate
守卫,但是除了登录组件之外,永远不会调用它,因为从第一个canLoad
返回 false 并将调用者路由到先前的登录组件。
第一个答案后编辑
canLoad(route: Route) {
if (!AuthService.isAuthenticated()) {
this.router.events.takeWhile(event => !(event instanceof NavigationCancel))
.subscribe(event => {
console.log(event);
if (event instanceof NavigationCancel) {
AuthService.setRedirectUrl(event.url);
}
});
return false;
}
return true;
}
所以我尝试了上述方法,但我认为我仍然做错了什么,因为控制台从不记录......我如何取消订阅或停止接收NavigationCancel
设置存储重定向 URL 后的事件?
Since canLoad
在构建路由器状态期间被调用,它不会获得激活的路由和整个路由器状态。它仅获取路线。
您可以将路由器注入守卫,订阅导航取消 https://github.com/angular/angular/blob/4.0.0/packages/router/src/events.ts#L53您可以访问 URL 的事件。
我如何取消订阅或停止接收 NavigationCancel 事件
设置存储重定向 URL?
Since router.events 是一个主题 https://github.com/angular/angular/blob/4.0.0/packages/router/src/router.ts#L222,您可以像这样取消订阅:
// get the subscription reference
const subscription = this.router.events.takeWhile(event => !(event instanceof NavigationCancel))
.subscribe(event => {
console.log(event);
if (event instanceof NavigationCancel) {
AuthService.setRedirectUrl(event.url);
// use it to unsubscribe
subscription.unsubscribe(); <----------------------------
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)