Search code examples
angularangular-router-guardscanactivate

Are there options / variables for canActivate in Angular 4


I'd like to decline access to routes based on the rights the user has. So i have a table inside my mongoDb with the userRights and two simple guards actually. One for logged in Users and one for Administrators.

So now i would like to give the user the right to visit a specific route. Therefore i'd like to add my canActivate: [checkForRightGuard] which gets parsed in the right so check but how would i do that?

I thought about this solution because i don't think that i have to create a guard for every right that i have to check - or?

So i though about sth. like this (of course, this is not working, but i think it shows what i need)

{path: 'admin/expandSoftware', component: ExpandSoftwareComponent, canActivate: [AdminGuard('canExpandSoftware')]},

Solution

  • You can add the 'data' property to the route, something like this :-

    {
        path: 'admin/expandSoftware', 
        component: ExpandSoftwareComponent, 
        canActivate: [AdminGuard],
        data: {authorization: 'canExpandSoftware'}
    }
    

    and then in your route guard you can access it as follows:-

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        console.log(route.data["authorization"]);
        return this.canActivate(route, state);
    }
    

    but be careful you may not be allowed to pass dynamic (run time) data to your routes if you are using AOT (Ahead of Time) compilation, as the routes are analyzed at compile time when using AOT compilation.