Haseeb Ahmad Haseeb Ahmad - 4 years ago 86
AngularJS Question

How to add condition in routers of angular2

My routes are :-

const appRoutes: Routes = [
{ path: 'alert/:id', component: AlertDetailComponent },
{ path: 'alerts', component: AlertsComponent },
{ path: 'dashboard', component: EriskDashboardComponent },
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'logout', component: LogoutComponent },
];


I want that if local Storage contain
token_id
then ./login redirect to EriskDashboardComponent

Answer Source

Add a CanActivate guard in your 'login' route:

{ path: 'login', component: LoginComponent, canActivate: [CheckToken] }

Inside the guard (named CheckToken in my example), check localStorage and redirect the user:

// check-token.service.ts
import { Injectable }     from '@angular/core';
import { CanActivate, Router }    from '@angular/router';

@Injectable()
export class CheckToken implements CanActivate {
  constructor(private router: Router) {
  canActivate() {
    const myToken = ...; // check localStorage
    if (myToken) {
      this.router.navigate(['/dashboard']);
    }
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download