首页 > 解决方案 > Angular 5 - 订阅行为主题时的问题

问题描述

在一项服务的构造函数中订阅行为主题变量时,我遇到了问题。当ok 的值为 0但我正在做时,订阅第一次发生。next(1)服务 1中,订阅未在服务 2 的构造函数中发生。

Service 1 : Where behavior subject variable is emitting

 counter: number = -1;
 ok: BehaviorSubject<any> = new BehaviorSubject(0);
  if (this.counter === 0) {
      setTimeout(() => {
        this.checkCounterFinally();
      }, 1000);
    }
  }

  checkCounterFinally() {
    if (this.counter === 0) {
      this.ok.next(1);

    }

  }

Service 2: Where i am subscribing the behavior subject variable in constructor.

constructor(private service: Service1){
    this.service.ok.subscribe((val) => {
      console.log("service2", val);
      if (val=== 1) {
        this.getDataFromLocalStorage();
      }

    });
}

标签: rxjsangular5observablebehaviorsubject

解决方案


BehaviorSubject 的使用看起来不错。您的问题的根源可能是您的应用程序中有许多 Service1 实例。


推荐阅读