observableangular9angular-guards

Angular 9 - Guard: canActivate wait until specific condition is met


I've the following code

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {

 this.userStore$ = this.store.pipe(select('userStore'));
 return this.userStore$.pipe(
   map( res => { 
     if(res) return true 
   }))
}
      

At first time res is undefined, so the canActivate resolves itself returning false. What i need is to mantain it listening until res is valorized, and then return true to proceed to the route. How i can do it? Thanks.


Solution

  • I can see you are pretty familiar with RXJS. RXJS provides filter function which can allow or deny the flow of stream based on certain condition.

    If you add the filter pipe to the stream it will deny all flow based on the condition. You always have to specify the true condition which will let the flow go.

    Docs https://www.learnrxjs.io/learn-rxjs/operators/filtering/filter

    // you need to import the filter from rxjs operators
    import {filter, map } 'rxjs/operators';
    
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    
     this.userStore$ = this.store.pipe(select('userStore'));
     return this.userStore$.pipe(
       filter(res => res != undefined),
       map( res => { 
         if(res) return true 
       }))
    }