Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 router canActivate after logout

Tags:

angular

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?

like image 907
Alexandr Rypun Avatar asked Nov 02 '16 13:11

Alexandr Rypun


People also ask

What is the command for routing in Angular?

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.


Video Answer


1 Answers

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.

like image 194
robisim74 Avatar answered Sep 21 '22 20:09

robisim74