Search code examples
angularangular-guards

Router canActivateChild with more than 1 guard


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.


Solution

  • 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