1

I'm having a bit of trouble because when implementing guards, I have the following (pseudocode):

canActivate(
  route, state, etc....{
    checkStatus()

    if(status){
      result = false
      etc
    }
)

The problem is that checkStatus() is asynchronous, but I need the result in order to decide wether return true or false to the guard. I've been looking to similar questions and the answer usually is to use Promises, but I still don't know how to use those within this canActivate() function. Any help please?

Thanks.

UPDATE:

I discovered that since the checkStatus() function is async and treated as a promise, I can just use checkStatus().then(status and if and everything).

Thanks a lot either way.

2 Answers2

1

If you take a look at the API for canActivate (https://angular.io/api/router/CanActivate), you will see that the function may return a Promise<boolean> or an Observable<boolean> in addition to a regular boolean.

For example, using a promise:

canActivate(
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
): Promise<boolean> {
  return new Promise( async (resolve, reject) => {
    // do something
    resolve(true);
} );

Or with an observable:

canActivate(
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
): Observable<boolean> {
  // do something
  return someObservable$.pipe(
    map( () => true)
  );
}
Celsiuss
  • 895
  • 7
  • 19
0

You can use rxjs operators in canActivate() function. e.g 'from' operator can be used to get observable from promise.

canActivate() {
  return from(checkStatus); // checkStatus should return promise<boolean> in this case
}