Short tutorial how to throw data on the canActivate guard API on angular 4. CanActivate is an interface used to check whether a route can be activated or not. Usually used to protect a web page from unauthorized access. And the data thrown on the canActive API is the roles parameter. Okay, follow this simple tutorial.
Another angular tutorial: Tutorial Call Parent Function From Child In Angular 4
You only need to add a “data” property to the angular route interface 4. Read the official route interface documentation here. Properties “data” is additional data provided to the component via ActivatedRoute. For implementation see the following code snippet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | const appRoutes: Routes = [ { path: 'dashboard',] component: DashboardComponent, canActivate: [AuthguardService], data: {roles: ['superadmin']} }, { path: 'laporan-inventaris', component: LaporanInventarisComponent, canActivate: [AuthguardService], data: {roles: ['user']} } ....... ....... ] |
Then how to use the above “data” properties in canActivate guard service like the following code snippet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import { Injectable } from '@angular/core'; import {Router,CanActivate,ActivatedRouteSnapshot,RouterStateSnapshot} from '@angular/router'; @Injectable() export class AuthguardService implements CanActivate { constructor(private router:Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { let roles = route.data["roles"] as Array<string>; // console.log('data roles : '+roles[0]); // console.log(route); if (localStorage.getItem('currentUser')) { var currentuser:any; currentuser =JSON.parse(localStorage.getItem('currentUser')); if(currentuser.level >= roles[0]){ return true; } } this.router.navigate(['/logout'], { queryParams: { returnUrl: state.url }}); return false; } } |
Reference : angular.io
So my short tutorial how to quickly pass parameters on canActivate Interface Angular 4, hopefully useful.
Leave a Reply