0

I am trying to implement route should have guards, (specific access or role basis)

here is my AdminGuard which is used when the route is only for the user which has 'admin' as authority,

@Injectable()
export class AdminGuard implements CanActivate {

   constructor(private router: Router) { }

   canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {

   //forget about: how to get the authority of user (I have kept it in shared service)   

   if (this.sharedService.user.authority == 'admin') {
           return Observable.of(true);
   } 
   else {
           return Observable.of(false);
   }
  }
}

Now, I would like to say that, whenever observable return false it should navigate to "unauthorized" component

Where my user doesn't have access information.

I am thinking how to do that, one solution is before returning I can change the route by the following:

canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
       if (this.sharedService.user.authority == 'admin') {
          return Observable.of(true);
       } 
       else {
          this.router.navigate(['/unauthorized']);
          return Observable.of(false);
       }
   }

But I don't find this solution is optimal way.

Open for any alternative solution, Thanks in advance

virsha
  • 1,140
  • 4
  • 19
  • 40

0 Answers0