Pass boolean from observable to observable

Harald Wiesinger picture Harald Wiesinger · Nov 28, 2016 · Viewed 18k times · Source

I want to check in my adminauthguard if the user has set a adminflag(in Firebase using angularfire2)

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> | boolean {
    return this.loginservice.af.auth.map((auth) =>  {
      if(auth == null) {
        return false;
      } else {
        this.membersservice.get(auth.uid).subscribe(users => {
          if(users.admin == true) {
            return true;
          } else {
            return false;
          }
        })
      }
    });

how can I resolve the observable in the observable inside?

Answer

lastWhisper picture lastWhisper · Nov 28, 2016
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> | boolean {

return new Observable<boolean>( observer => {

   this.loginservice.af.auth.map((auth) =>  {
      if(auth == null) {
        observer.next(false);
      } else {
        this.membersservice.get(auth.uid).subscribe(users => {
          if(users.admin == true) {
            observer.next(true);
          } else {
            observer.next(false);
          }
        })
      }
    });

Not 1000% sure if this will work with your service Observables, since I don't know Firebase for Angular2 exactly (only iOS), but this way you create an observable that just emits values based on the events that are happening inside the closure.

The only thing you may need to make sure (with tests) is that you do not run into undefined states, e.g. something like async hazards where you both emit true and false.