问题
I have the following in my main app router:
{ path: 'users', loadChildren: 'app/modules/users/users.module#UsersModule', canLoad: [AuthGuard] }
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.
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?
EDIT AFTER FIRST COMMENT
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.
EDIT AFTER FIRST ANSWER
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;
}
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?
回答1:
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.
You can inject a router into a guard, subscribe to NavigationCancel event where you can access the URL.
how do I unsubscribe or stop receiving NavigationCancel events after I set store the redirect URL?
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(); <----------------------------
}
});
来源:https://stackoverflow.com/questions/44486306/routing-to-a-specific-page-within-a-lazy-loaded-module-in-angular-2