【问题标题】:How to fix Behavioursubject subscription issue from service to component如何解决从服务到组件的行为主题订阅问题
【发布时间】:2019-04-15 15:31:52
【问题描述】:

我在我的应用程序中使用 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");
    });
  }

请帮我解决问题。

提前致谢。

【问题讨论】:

  • 我建议您重新表述您的问题。真的很难跟上。另外,我看不到您在组件中的何处使用该服务来发出 http 请求。 ngOnInit() 函数不使用您的服务。
  • 请提供 stackblitz 链接,以便更好地帮助您
  • ok 有多个模块在这个复制问题很困难

标签: angular rxjs angular7 rxjs6


【解决方案1】:

您的代码是正确的并且应该可以工作,尽管有这两个奇怪的事情:

  • 在服务中订阅 HTTP 请求是一种奇怪的模式
  • 每个 HTTP 请求都会复制 HTTP 订阅中的订阅

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

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

  • 有了这个注解@Injectable({ providedIn: 'root' })
  • 在根模块的providers 部分中

【讨论】:

  • 我在根模块中导入的数据即将更新,但组件订阅不起作用
  • 收缩器?我认为你的代码中有一条蟒蛇这是什么意思
  • 只是一个糟糕的笑话来指出你的错字:你写的是constrictor而不是constructor。不确定您是从代码中粘贴的,还是在问题中输入错误
  • 那是我手动输入的。我尝试了很多可能性我没有任何解决方案
猜你喜欢
  • 2019-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-17
  • 1970-01-01
  • 2021-08-06
相关资源
最近更新 更多