'How to use same route guard for different routes that differ in authorization logic

For my Angular 6 project, I have one canactivate AuthGuard to load ComponentA.

I want to know can I use the same AuthGuard for component B where it's the authorization logic is exactly opposite to component A?

Let's say the logic to authorize component A as follows

  • Get summary items from API service HTTP GET call
  • Iterate on the items and check the activationStatus. If activation status is 'ACTIVE' return true
  • If no summary items are returned and activation status is not 'ACTIVE', return false and just show the login page.

My requirement is load component B is exactly opposite to above.

  • Show component B If no summary items are returned and activation status is not 'ACTIVE', do not load the component and just show the login page
  • If summary items are present and activation status is 'ACTIVE' just show login page.

Existing auth.guard.ts for component A:

export class AuthGuard implements CanActivate {
 
canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean>
{
    return this.checkAuthorization();
}
checkAuthorization():Observable<boolean>{

    let hasActiveSummary:boolean=false;

    return this.apiService.getSummary(url)
    .pipe(
      map((data:any) => {
        console.log("Summary list:", data);
          if(data.length > 0){
            for (let i=0; i< data.length; i++) {
              if(data[i].activationStatus ==='ACTIVE') {
                hasActiveSummary=true;
                return true;
              }
            }
          }
          if(!hasActiveSummary){
            this.router.navigate(['/login']);
            return false;
          }
      })
    )
}

I would like to know can I use the same auth guard? If so, how to do it?



Solution 1:[1]

canActivate method has state property which is of type RouterStateSnapshot. You can make a decision based on state.url and just return the inverse of hasActiveSummary based on the route you are reaching.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Beka Kalandadze