【问题标题】:Angular9 rxjs-behaviorsubject not working on different component?Angular9 rxjs-behaviorsubject 不适用于不同的组件?
【发布时间】:2021-01-11 15:29:56
【问题描述】:

我正在尝试将数据从配置文件组件实时更新到标头组件,最初它可以正常工作,但在更新配置文件组件标头可观察的任何值后,不再订阅。所以我在这样的组件中使用带有 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;
    }
  })

谁能告诉我我的代码有什么问题?

【问题讨论】:

  • 你能做一个演示吗?很难说可能出了什么问题。你确定你只有一个服务实例吗?
  • 看起来您的订阅应该会收到新的价值。我和@martin 一起做这个,你确定你只有一个服务实例吗?
  • @BizzyBob:是的,先生,我已经创建了一个服务实例,但我不明白这是什么问题?
  • @martin:好的,我将为此创建一个演示并创建一个服务实例

标签: angular rxjs behaviorsubject angular2-changedetection


【解决方案1】:

这是预期的行为,因为您已使用另一个值重新分配 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;
  }
})

【讨论】:

  • 先生,我尝试了上面的代码,但结果相同...userValue.subscribe 在更新值后不调用?
  • 你能创建一个最小的在线示例吗?
猜你喜欢
  • 2017-01-22
  • 1970-01-01
  • 2019-03-26
  • 2017-08-07
  • 1970-01-01
  • 2016-08-10
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
相关资源
最近更新 更多