Wednesday, July 24, 2019

Make the canActivate method in a CanActivate guard in an Angular 7 application return an Observable of boolean instead of just a boolean.

canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
   let userObservable:Observable<User> = this.store.select(getUserInfo);
   let booleanObservable:Observable<boolean> = userObservable.pipe(map((user) => {
      return (user.Functions.indexOf('Business Units - Update') > -1);
   }));
   return booleanObservable;
}

 
 

Here is the same thing a bit more fleshed out:

canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
   let userObservable:Observable<User> = this.store.select(getUserInfo);
   let booleanObservable:Observable<boolean> = userObservable.pipe(map((user) => {
      if (user.Functions.indexOf('Business Units - Update') == -1) {
         this.router.navigate(['/audit-attestations','unauthorized']);
      }
      return true;
   }));
   return booleanObservable;
}

 
 

Some of the imports:

import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

No comments:

Post a Comment