angular – 如何从subscribe返回observable

前端之家收集整理的这篇文章主要介绍了angular – 如何从subscribe返回observable前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我在订阅者中获得某个值时,我正试图返回一个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;
}
原文链接:https://www.f2er.com/angularjs/143929.html

猜你在找的Angularjs相关文章