我遇到了 subscribe 触发 2 次的场景。但是,如果我通过将轮询器方法复制粘贴到我的组件中来摆脱该服务,那么问题就会消失。
我正在 Ionic 3 中运行,但我认为这在这里并不重要。“rxjs”:“5.4.3”
unsubscribe()被召唤ngDestroy()
我的服务.service.ts
public pollingDataReceived = new Subject<any>();
pollForData = (id: string) : Subscription => {
let stopPollingForStatus = false;
return Observable.interval(environment['pollingInterval'])
.takeWhile(() => !stopPollingForStatus)
.concatMap(() => {
return this.getAnalysisById(id);
})
.subscribe((analysisData) => {
if (analysisData) {
if (analysisData.status === 'questions') {
stopPollingForStatus = false;
}
else {
stopPollingForStatus = true;
const result = {
someData: 'whatever'
};
console.log('raise pollingDataReceived event');// This happens ONCE
this.pollingDataReceived.next(result);
}
}
else {
alert('no analysis data!');
}
});
}
Run Code Online (Sandbox Code Playgroud)
my.component.ts(订阅者)
private pollingData: Subscription;
someEventHandler() {
this.pollingData = this.pollForData(this.id);
}
ngOnInit(): void {
this.myService.pollingDataReceived.subscribe((data) => {
this.analysis = data.analysisData;
//This is getting called 2x. Maybe I double subscribed?
myNavigator.navigateToPageByStatus(myPage);
}, (err) => { console.log(err); });
}
ngOnDestroy() {
console.log('ngOnDestroy: unsubscribe pollingData in flow');// This does get called
this.pollingData.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)
我遇到了类似的问题,请尝试下面的代码,这只是根本问题的解决方法。
this.pollingDataReceived.next(result);
this.pollingDataReceived = new BehaviorSubject<any>(); // Here, create new object with null value
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8482 次 |
| 最近记录: |