I used login-guard for some routes (e.g. '/profile'). Looks like this:
canActivate() {
if (this.user.islogin) return true;
this.router.navigate(['']);
}
It redirects user to main page if he's not logged in and tries to get access to some routes. It works fine. User can log out from any page. I want my app to have next behavior: If user is on '/profile' page and clicks 'logout', he should be redirected to main page by canActivate() method. But this method isn't called in this case. What should I do to run canActivate()(reload page, manually call)? My logout method:
logout() {
localStorage.removeItem('auth_token');
this.islogin = false;
}
I've tried to add this.router.navigate([this.router.url]);
to logout method, but result is the same.
Only if I reload page, angular2 redirects me.
What is the right way?
RouterModule. forRoot(routes) ], The method is called forRoot() because you configure the router at the application's root level. The forRoot() method supplies the service providers and directives needed for routing, and performs the initial navigation based on the current browser URL.
The question is old, but the problem is current.
From Angular v6 you can set the onSameUrlNavigation
property of the router:
RouterModule.forRoot(routes, {
...
onSameUrlNavigation: 'reload'
})
and set runGuardsAndResolvers
where do you need:
{
path: '',
component: AccountComponent,
canActivate: [AuthGuard],
runGuardsAndResolvers: 'always'
}
In your logout method, just call the same route, and the canActivate
method of your auth guard will be fired:
signout(): void {
this.store.dispatch({
type: AuthActionTypes.Signout
});
// Navigate to the same url to invoke canActivate method
// in routes with runGuardsAndResolvers.
// Also activated onSameUrlNavigation router property.
this.router.navigate([this.auth.redirectUrl]);
}
In the sample above, redirectUrl
is a property where the current url is saved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With