Skip boolean from observable to observable

I want to check my admin if user installed 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?

+5
source share
2 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 sure 1000% if this will work with your Observables service, since I don’t know Firebase for Angular2 (iOS only), but in this way you create an observable that just emits values ​​based on events that happen inside the closure.

The only thing you may need to make sure (with the help of tests) is that you are not running undefined states, for example. something like asynchronous dangers when you both emit truth and falsehood.

+10
source

I need to wait for user information about the user before starting any protected component. I use a similar solution for lastWhisper, implementing canActivateChild and setting in routes:

  path: 'app', component: FullLayoutComponent, data: {title: 'Home'}, canActivateChild: [CanActivateChildTeam], CanActivateChildTeam Service: import {Injectable, OnDestroy} from "@angular/core"; import {CanActivateChild} from "@angular/router"; import {Meteor} from 'meteor/meteor'; import {Router} from '@angular/router'; import {Observable} from "rxjs/Rx"; import {MeteorObservable} from 'meteor-rxjs'; import {Subscription} from 'rxjs/Subscription'; @Injectable() export class CanActivateChildTeam implements CanActivateChild, OnDestroy { allow:Observable<boolean>; private _userSub:Subscription; constructor(private router:Router) { } canActivateChild(route:any, state:any):Observable<boolean> | Promise<boolean> | boolean { return this.getUser(); } getUser() { if (this.allow) { this.allow = new Observable(observer => { observer.next(true); observer.complete(); }); return this.allow; } if (Meteor.userId()) { this.allow = new Observable(observer => { if (this._userSub) this._userSub.unsubscribe(); this._userSub = MeteorObservable.subscribe('user', Meteor.userId()).subscribe( () => { observer.next(true); observer.complete(); } ); }); return this.allow; } else { this.router.navigate(['/']); } } ngOnDestroy():void { if (this._userSub) this._userSub.unsubscribe(); } } 
+2
source

Source: https://habr.com/ru/post/1260416/


All Articles