I have a angular2 active guard which handle if the user is not logged in, redirect it to login page:
import { Injectable } from "@angular/core"; import { CanActivate , ActivatedRouteSnapshot, RouterStateSnapshot, Router} from "@angular/router"; import {Observable} from "rxjs"; import {TokenService} from "./token.service"; @Injectable() export class AuthenticationGuard implements CanActivate { constructor ( private router : Router, private token : TokenService ) { } /** * Check if the user is logged in before calling http * * @param route * @param state * @returns {boolean} */ canActivate ( route : ActivatedRouteSnapshot, state : RouterStateSnapshot ): Observable<boolean> | Promise<boolean> | boolean { if(this.token.isLoggedIn()){ return true; } this.router.navigate(['/login'],{ queryParams: { returnUrl: state.url }}); return; } }
I have to implement it on each route like :
const routes: Routes = [ { path : '', component: UsersListComponent, canActivate:[AuthenticationGuard] }, { path : 'add', component : AddComponent, canActivate:[AuthenticationGuard]}, { path : ':id', component: UserShowComponent }, { path : 'delete/:id', component : DeleteComponent, canActivate:[AuthenticationGuard] }, { path : 'ban/:id', component : BanComponent, canActivate:[AuthenticationGuard] }, { path : 'edit/:id', component : EditComponent, canActivate:[AuthenticationGuard] } ];
Is there any better way to implement canActive option without adding it to each path.
What I want is to add it on main route, and it should apply to all other routes. I have searched alot, but I could not find any useful solution
Thanks
You can introduce a componentless parent route and apply the guard there:
const routes: Routes = [ {path: '', canActivate:[AuthenticationGuard], children: [ { path : '', component: UsersListComponent }, { path : 'add', component : AddComponent}, { path : ':id', component: UserShowComponent }, { path : 'delete/:id', component : DeleteComponent }, { path : 'ban/:id', component : BanComponent }, { path : 'edit/:id', component : EditComponent } ]} ];
You can also subscribe to the router's route changes in your app.component's ngOnInit function and check authentication from there e.g.
this.router.events.subscribe(event => { if (event instanceof NavigationStart && !this.token.isLoggedIn()) { this.router.navigate(['/login'],{ queryParams: { returnUrl: state.url}}); } });
I prefer this way of doing any kind of app wide check(s) when a route changes.
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