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