如果用于公共方法而不是ngOnDestroy,则无法取消订阅。
如果具有用于轮询API的rxjs可观察间隔。 onNgInit我遵守以下可观察的观点:
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()中,我是否有做错什么。 在某个特定组件仍处于活动状态时,如何取消该条件的订阅。
谢谢。
答案 0 :(得分:0)
您的class
使用了implements OnInit, OnDestroy
吗?可能是如果您的类未使用OnDestroy
实现,则ngOnDestroy()
将不会执行。这是OnDestroy
以下代码片段显示了组件如何实现此接口以定义其自己的自定义清理方法。
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnDestroy {
ngOnDestroy() {
// ...
}
}