当我在订阅者中获得某个值时,我正试图返回一个observable,但我失败了。
这是代码:
canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot):Observable<boolean> { // get route to be activated this.routeToActivate = route.routeConfig.path; // get user access levels return this._firebase.isUserAdmin <-- returns Subscription,not Observable .map(user => user.access_level) .subscribe( access => { // I need to return an observable here }); }
角度2中的可观察量资源不多,所以我不知道从哪里开始。有人可以帮忙吗?
更新 – >工作版
canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot):Observable<boolean> { // get route to be activated this.routeToActivate = route.routeConfig.path; // get user access levels return this._firebase.isUserAdmin .map(user => { let accessLevel = user.access_level; if (accessLevel === 'admin' ) { return true; } }).first(); }
您无法从订阅返回observable,但如果您使用map而不是subscribe,则返回Observable。
canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot):Observable<boolean> { // get route to be activated this.routeToActivate = route.routeConfig.path; // get user access levels return this._firebase.isUserAdminObservable .map(user => { // do something here // user.access_level; return true; }) .first(); // for the observable to complete on the first event (usually required for `canActivate`) // first needs to be imported like `map`,... } canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot):Observable<boolean> { // get route to be activated this.routeToActivate = route.routeConfig.path; let subject = new Subject(); // get user access levels this._firebase.isUserAdminObservable .map(user => { let accessLevel = user.access_level; if (accessLevel === 'admin' ) { subject.emit(true); subject.complete(); } return user; }); return subject; }