0
votes

I have setup my routes and route guards in Angular and they are working great for stopping the user from accessing a route that they shouldn't. However, I have a global navigation section on all my pages and it basically loops over my array of Routes and displays all of the links (using *ngFor). I would like to have each Route evaluated when I'm looping over them to see if the use canActivate that route. This way I am not showing the user a link for something they cannot visit. I'd like to do this in a way that that the same route guard logic is reused.

I have an array of routes like so:

const routes: Routes = [
   { 
      path: 'dashboard-simple', 
      component: DashboardSimpleComponent,
      canActivate: RoleGuard,
      data: {roles: ['Basic']}
   },
   { 
      path: 'dashboard-advanced', 
      component: DashboardAdvancedComponent,
      canActivate: RoleGuard,
      data: {roles: ['Admin']}
   },
   // And so on...
];

The template looks like this:

<ul>
    <li *ngFor="let route of routes"><a [routerLink]="route.path">{{ route.path }}</a></li>
</ul>
2
how flexible does this need to be? is it always the RoleGuard and depending on data.roles? or is there more to it than that? if it's the simple case, I'd just write a RoleGuardDirective of some kind and feed the roles to it in the loop - bryan60

2 Answers

0
votes

if the roleguard is declared in global module it will execute once it was declared beacause of constructor, make the guard available in your current module, hope it will work

0
votes

To the best of my knowledge, the type of functionality does not exist within the Angular framework. Specifically, I saw that Router in Angular has a property called isActive where you pass in a string url and it responds with a boolean. I was hoping for something similar where I could pass a string url and have the framework reuse the logic I setup for canActivate to return me a boolean. I couldn't find this type of logic on Router or anywhere else in the framework.

My solution to get for achieving DRY is to just create a method that can be shared both in my route config and in my template's *ngFor