路由到 angular 中延迟加载模块中的特定页面 2+
Routing to a specific page within a lazy-loaded module in angular 2+
我的主应用程序路由器中有以下内容:
{ path: 'users', loadChildren: 'app/modules/users/users.module#UsersModule', canLoad: [AuthGuard] }
当用户转到 http://localhost:4200/users/1234 查看他们的个人资料时,我会尝试保存完整的 url(包括上面的用户 ID),以便在他们“重新登录。
问题是,canLoad
函数中的Route
参数只有一个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?
由于在构建路由器状态期间调用了 canLoad
,因此它不会获得激活的路由和整个路由器状态。它只获取路线。
您可以将路由器注入守卫,订阅 NavigationCancel 事件,您可以在其中访问 URL。
how do I unsubscribe or stop receiving NavigationCancel events after I
set store the redirect URL?
自 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(); <----------------------------
}
});
我的主应用程序路由器中有以下内容:
{ path: 'users', loadChildren: 'app/modules/users/users.module#UsersModule', canLoad: [AuthGuard] }
当用户转到 http://localhost:4200/users/1234 查看他们的个人资料时,我会尝试保存完整的 url(包括上面的用户 ID),以便在他们“重新登录。
问题是,canLoad
函数中的Route
参数只有一个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?
由于在构建路由器状态期间调用了 canLoad
,因此它不会获得激活的路由和整个路由器状态。它只获取路线。
您可以将路由器注入守卫,订阅 NavigationCancel 事件,您可以在其中访问 URL。
how do I unsubscribe or stop receiving NavigationCancel events after I set store the redirect URL?
自 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(); <----------------------------
}
});