如何修复从服务到组件的Behavioursubject订阅问题

问题描述 投票:0回答:1

我在我的应用程序中使用Behavioursubject,我使用异步管道订阅了Behavioursubject,并且我订阅了我的组件。

问题:当我尝试更新Behavioursubject中的数据时,数据正在Behavioursubject中更新。组件订阅未更新。在应用程序启动订阅执行时。在基于改变的启动之后,我正在更新服务中的数据,数据正在服务中更新,但是组件内的订阅没有更新。

我尝试了多种方法,例如将服务注册更改为根模块,这也没有用

这是我的组件代码:

这是方法订阅调用。

 ngOnInit() {
 this.getnotifications();
 }
 getnotifications() {
     this.notifications.getjsnotifications('all');
    this.notifications.jsnotifications.subscribe(data => {
      console.log("came after the update");
      this.jsnotifications = data;
    });
   }

这是服务代码:


  public jsnotifications = new BehaviorSubject(null);

  constructor(){
   this.getjsnotifications("all");
  }

  getjsnotifications(type){
    this.http.get<Config>(`${environment.JS_API}/jobseeker/notifications/getJobSeekerNotifications?notificationType=`+type).subscribe(data =>{
     console.log(data.map.notificationsVo);
      this.jsnotifications.next(data.map.notificationsVo);
      this.jsnotifications.subscribe(data => {
        console.log(data);
      })
      this.testbehaviour.next(data.map.notificationsVo);
      console.log("data updated");
    });
  }

请帮我解决这个问题。

提前致谢。

angular rxjs angular7 rxjs6
1个回答
1
投票

你的代码是正确的,应该可以工作,尽管有两件奇怪的事情:

  • 订阅服务中的HTTP请求是一种奇怪的模式
  • HTTP订阅中的订阅将在每个HTTP请求上重复

问题很可能来自您声明服务的方式,这导致创建了两个不同的实例。

请务必使用以下方法之一声明您的服务:

  • 有了这个注释@Injectable({ providedIn: 'root' })
  • 在根模块的providers部分
© www.soinside.com 2019 - 2024. All rights reserved.