【发布时间】:2019-02-04 17:49:34
【问题描述】:
如果在公共方法而不是 ngOnDestroy 中使用,则无法取消订阅。
如果有用于轮询 API 的 rxjs 可观察间隔。 onNgInit 我订阅该 observable 如下:
Class .. {
pollingSubscription: Subscription;
ngOnInit() {
startPolling();
}
// when this gets triggered my polling subscription stops
ngOnDestroy() {
if (this.pollingSubscribe) {
this.pollingSubscription.unsubscribe();
}
}
startPolling() {
const pollingInterval: Observable<any> = observable.interval(3000).startWith(0);
this.pollingSubscription = pollingInterval.subscribe( _ => {
this.store.dispatch(// trigger my Action);
});
}
// when this gets triggered on a click event my polling subscription still keeps polling.
stopPolling() {
if ( // condition true) {
// on this condition stop polling, FYI this line does get triggered,
// but there is no effect, it still keeps subscribed.
this.pollingSubscription.unsubscribe();
}
}
}
在公共函数 stopPolling() 中我做错了什么吗? 如何在给定组件上仍处于活动状态的情况下取消订阅。
谢谢。
【问题讨论】:
-
你在哪里对 stopPolling() 进行函数调用?
-
只是一个例子,它可以在任何地方调用,比如点击事件。
-
我问是因为我没有看到取消订阅的功能调用。
-
@patz 你确定条件是真的吗?代码没有问题,应该可以取消订阅
-
好吧,我不确定你的代码有什么不同,但我已经在 StackBlitz 上对其进行了重构,找不到任何问题:stackblitz.com/edit/…
标签: angular rxjs observable subscribe unsubscribe