Angular9 rxjs-behaviorsubject无法在其他组件上工作?

问题描述

我正在尝试从配置文件组件到标头组件实时地实时添加数据,但是在更新后,可观察到的配置文件组件标头中的任何值都不会再次订阅。所以我在这样的组件中使用带有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;
  }
})

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...