如何从可观察流中检索特定字段?
How to retrieve specific fields from observable stream?
我创建了包含用户对象的 Following 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;
}
还有比这更简单的方法吗?
提前致谢
我宁愿保持 observable 原样,他们对其应用一些转换
getUserRole(){
return this.currentUserProfile.map((profile:UserProfile)=> profile.roles);
}
hasRole(role:string):boolean{
return this.currentUserProfile$.reduce((role) =>
profile.roles.indexOf(role) !== -1;
);
}
我创建了包含用户对象的 Following 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;
}
还有比这更简单的方法吗?
提前致谢
我宁愿保持 observable 原样,他们对其应用一些转换
getUserRole(){
return this.currentUserProfile.map((profile:UserProfile)=> profile.roles);
}
hasRole(role:string):boolean{
return this.currentUserProfile$.reduce((role) =>
profile.roles.indexOf(role) !== -1;
);
}