问题描述
我正在尝试从配置文件组件到标头组件实时地实时添加数据,但是在更新后,可观察到的配置文件组件标头中的任何值都不会再次订阅。所以我在这样的组件中使用带有BehaviorSubject和Subscription的服务。请检查我的代码我的代码有什么错误:
服务代码:
//Service (code related to the problem):
this.userInfo = new BehaviorSubject(JSON.parse(localStorage.getItem('userData')));
this.updatedPageData = new BehaviorSubject('');
this.userValue = this.userInfo.asObservable();
个人资料组件
//updateData for emit updated value
updateData(data){
this.storage.saveDataInStorage(data);
this.cmnFunction.userInfo.next(data);
}
标题组件
//Get values
this.cmnFunction.userValue.subscribe(data=>{
if(data != null) {
this.currentUseInfo.name = data.name;
this.currentUseInfo.image = data.image;
this.currentUseInfo.role = data.role;
}
})
有人可以告诉我代码中的问题吗?
解决方法
这是预期的行为,因为您已经为userValue
重新分配了另一个值,如以下行所示:this.userValue = this.userInfo.asObservable();
考虑应用以下更改:
服务代码:
private userInfoSource = new BehaviorSubject(JSON.parse(localStorage.getItem('userData')));
public userValue = this.userInfoSource.asObservable();
public set updateUserInfo(value: string){
this.userInfoSource.next(value)
}
个人资料组件
updateData(data){
this.service.updateUserInfo = data
}
标题组件
this.service.userValue.subscribe(data=>{
if(data != null) {
this.currentUseInfo.name = data.name;
this.currentUseInfo.image = data.image;
this.currentUseInfo.role = data.role;
}
})