Pass parameter into route guard

Brian Noyes picture Brian Noyes · Mar 10, 2017 · Viewed 40.4k times · Source

I'm working on an app that has a lot of roles that I need to use guards to block nav to parts of the app based on those roles. I realize I can create individual guard classes for each role, but would rather have one class that I could somehow pass a parameter into. In other words I would like to be able to do something similar to this:

{ 
  path: 'super-user-stuff', 
  component: SuperUserStuffComponent,
  canActivate: [RoleGuard.forRole('superUser')]
}

But since all you pass is the type name of your guard, can't think of a way to do that. Should I just bit the bullet and write the individual guard classes per role and shatter my illusion of elegance in having a single parameterized type instead?

Answer

Hasan Beheshti picture Hasan Beheshti · Mar 10, 2017

Instead of using forRole(), you can do this:

{ 
   path: 'super-user-stuff', 
   component: SuperUserStuffComponent,
   canActivate: RoleGuard,
   data: {roles: ['SuperAdmin', ...]}
}

and use this in your RoleGuard

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
    : Observable<boolean> | Promise<boolean> | boolean  {

    let roles = route.data.roles as Array<string>;
    ...
}