Search code examples
angularoauth-2.0angular2-routing

Can not cancel current navigation and navigate elsewhere from root component


When a user is not logged into my application which is equal to that there exists no userToken in the localStorage then I just want to redirect him to the login route.

Lets say the user enters the route /customers then he should be redirected to the login screen when there exist no userToken in the local storage.

App.component.ts:

export class AppComponent
{
  constructor(private routerService: RouterService, private router: Router, private authService: AuthenticationService)
  {
    if (!authService.isLoggedIn())
    {
      this.router.navigate(['/login']);
    }
  }
}

The router navigate method is called but it is not navigating to the login screen, why not? The customers data on backend is tried to fetch, but I get a 401 in the server response. That means the code after... the root app component just continued to run.


Solution

  • Best way to angular 2 check user is login or not before going through route.you can use 'canActivate' in route define like this

    { path: 'customers', component: AppComponent, canActivate: [AuthService] }
    

    And now on AuthService you can defined method

    canActivate() {
            //you can check token is exists or not here 
            if (localstorage.getItem('user')) {
                return true;
            } else {
                this.router.navigate(['login']);
                return false;
            }
        }
    

    More details https://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html