Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass boolean from observable to observable

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?

like image 519
Harald Wiesinger Avatar asked Nov 27 '16 23:11

Harald Wiesinger


Video Answer


1 Answers

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.

like image 114
lastWhisper Avatar answered Oct 29 '22 05:10

lastWhisper