2017-06-13 49 views
0

我已經創建了以下可保存用戶對象的Observable Stream。如何檢索可觀察流中的特定字段?

currentUserProfile$ = new BehaviorSubject<UserProfile>(null); 

初始化此流我已經定義了以下方法:

getCurrentUserProfile(userId):void{ 
    let profile:UserProfile= new UserProfile({}); 
    this._empService.getUserInfo(userId).subscribe(
     (response)=>{ 
      profile=response.profileData; 
      profile.isAuthenticated=true; 
      this.currentUserProfile$.next(profile); 
     }, 
     (error)=>{ 
      profile.isAuthenticated=true; 
      this.currentUserProfile$.next(profile); 
      console.error(error); 
     } 
    ); 
} 

現在我想創建方法爲每個流包含這些屬性。爲前。

getUserRole(){ 
    let roles:Array<any>; 
    this.currentUserProfile$.subscribe((profile:UserProfile)=>{ 
     roles=profile.roles; 
    }); 
    return roles; 
} 

hasRole(role:string):boolean{ 
    let res:boolean; 
    this.currentUserProfile$.subscribe(
     (profile)=>{ 
     res=profile.roles.indexOf(role) !== -1; 
     } 
    ); 
    return res; 
} 

有沒有比這更簡單的方法?

在此先感謝

回答

0

我寧願保持觀察到的是,並將它們應用於一些改造過它

getUserRole(){ 
    return this.currentUserProfile.map((profile:UserProfile)=> profile.roles); 
} 

hasRole(role:string):boolean{ 
    return this.currentUserProfile$.reduce((role) => 
     profile.roles.indexOf(role) !== -1; 
    ); 
}