在 angular 2+ 中路由到延迟加载模块中的特定页面 [英] Routing to a specific page within a lazy-loaded module in angular 2+
问题描述
我的主应用路由器中有以下内容:
I have the following in my main app router:
{ path: 'users', loadChildren: 'app/modules/users/users.module#UsersModule', canLoad: [AuthGuard] }
当用户去 http://localhost:4200/users/1234 查看他们的个人资料,我尝试保存完整的 url(包括上面的用户 ID),以便在他们登录后返回该页面.
When the user goes to http://localhost:4200/users/1234 to see their profile, I try to save the full url (including the user ID above) so that I would route back to that page once they're logged in.
问题是,canLoad
函数中的Route
参数只有一个path
字段,不包含上面的用户ID,只有路径 users
.有什么办法可以做到这一点吗?
The problem is, the Route
parameter in the canLoad
function only has a path
field that does not include the user ID above, only the path users
. Is there a way I can achieve this?
第一条评论后编辑
用户路由模块确实有一个 canActivate
保护,但是除了登录组件之外,它永远不会被调用,因为第一个 canLoad
返回 false 并将调用者路由到之前的登录组件.
The users routing module does have a canActivate
guard, but this never gets called except from the login component, since the first canLoad
returned false and routed the caller to the login component previously.
第一次回答后编辑
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
事件?
So I tried the above, but I think I'm doing something wrong still, since console never logs... how do I unsubscribe or stop receiving NavigationCancel
events after I set store the redirect URL?
推荐答案
由于 canLoad
在构建路由器状态的过程中被调用,因此不会获得激活的路由和整个路由器状态.它只获取路线.
Since canLoad
is called during the construction of the router state it doesn't get activated route and the whole router state. It gets only the route.
可以在guard中注入路由器,订阅NavigationCancel 事件,您可以在其中访问 URL.
You can inject a router into a guard, subscribe to NavigationCancel event where you can access the URL.
如何取消订阅或停止接收 NavigationCancel 事件设置存储重定向 URL?
how do I unsubscribe or stop receiving NavigationCancel events after I set store the redirect URL?
由于 router.events 是一个主题,你可以像这样退订它:
Since router.events is a Subject, you can unsubscribe from it like this:
// 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(); <----------------------------
}
});
这篇关于在 angular 2+ 中路由到延迟加载模块中的特定页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!