【发布时间】:2018-06-26 09:24:16
【问题描述】:
在一项服务的构造函数中订阅行为主题变量时遇到问题。当 ok 的值为 0 时第一次发生订阅,但是当我在 service 1 中执行 .next(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();
}
});
}
【问题讨论】:
-
你能用最少的代码创建一个 plunker 吗?我认为主要问题是您直接使用主题而不是返回可观察对象(通过
asObservable()),但很难确定。
标签: rxjs angular5 observable behaviorsubject