我的主应用程序路由器中有以下内容:
{ path: 'users', loadChildren: 'app/modules/users/users.module#UsersModule', canLoad: [AuthGuard] }
当用户转到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;
}
所以我尝试了上述内容,但我认为我仍然做错了,因为控制台永远不会记录...在设置存储重定向URL后,如何取消订阅或停止接收NavigationCancel
事件?
答案 0 :(得分:1)
由于在构建路由器状态期间调用canLoad
,因此它不会获得激活路由和整个路由器状态。它只获得路线。
您可以将一个路由器注入一个后卫,订阅NavigationCancel事件,您可以访问该URL。
我之后如何取消订阅或停止接收NavigationCancel事件 设置存储重定向网址?
自router.events is a Subject以来,您可以这样取消订阅:
// 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(); <----------------------------
}
});