1

I am using more than one canActivateChild guards as shown below:

{path: 'admin', canActivateChild : [AdminAuthGuard, EmployeeAuthGuard], children: adminRoutes }

Below is definition of admin guard:

canActivateChild() : boolean {
   const role = localStorage.getItem('role');
   if(role === 'admin') {
     return true;
   }
   else {
     return false;
   }
}

I have very similar employee guard where I am checking role as employee. The issue with above code is:

  1. If my first guard return false, second guard is not at all executed.
  2. If my first guard returns true and my second guard return false. The route is failing at that time as well.

NOTE: My guards are synchronous still I am facing this issue. Please let me know how can I resolve it?

The actual code is much more complex than this. This is just a sample code to get help.

Tavish Aggarwal
  • 1,020
  • 3
  • 22
  • 51
  • possible duplicate of https://stackoverflow.com/questions/44460661/how-to-wait-for-guards-in-angular/44462275#44462275 – Safiyya Feb 26 '18 at 10:16
  • @Safiyya I dont want to check all guards. I have 10 gurds in my application. Using shared service will check every guard. For admin route, I want to check only two guards. – Tavish Aggarwal Feb 26 '18 at 10:22

1 Answers1

3

Create a combined guard off the 2 others guards that check both return values :

class CombinedGuard {
  constructor(private adminGuard: AdminAuthGuard, private employeeGuard: EmployeeAuthGuard) {}

  canActivate(r, s) {
        // defined your order logic here, this is a simple AND
        return this.adminGuard.canActivate(r, s) && this.employeeGuard.canActivate(r,s)
  }
}

and then use that CombinedGuard in your routing :

{path: 'admin', canActivateChild : [CombinedGuard], children: adminRoutes }

Inspired by How to wait for guards in Angular

Safiyya
  • 1,383
  • 1
  • 10
  • 16
  • Can there be other solution as well? Seems like solution but here I need to create lot of combinedGuards as I have to lot of Permutations here? – Tavish Aggarwal Feb 26 '18 at 10:29
  • you could use a factory that returns and `Array` for each of your case and return `array.map(g => g.canActivate(r,s))` in your combined guard. This way you separate your permutation logic from the activation logic – Safiyya Feb 26 '18 at 10:33
  • Does that make any sense? – Safiyya Feb 26 '18 at 11:34