如果在公共方法中使用而不是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()中做了什么错误 . 如何在特定组件上仍处于活动状态时取消订阅某个条件 .
谢谢 .
1 回答
你的
class
使用implements OnInit, OnDestroy
??可能如果您的类未使用OnDestroy
实现,那么ngOnDestroy()
将不会被执行 . 对于OnDestroy
,这是the official link以下代码段显示了组件如何实现此接口以定义自己的自定义清理方法 .