如果没有ngOnDestroy,angular unsubscribe不起作用

问题描述 投票:0回答:1

如果在公共方法中使用而不是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()中做了什么错误。如何在特定组件上仍处于活动状态时取消订阅某个条件。

谢谢。

angular rxjs observable subscribe unsubscribe
1个回答
0
投票

你的class使用implements OnInit, OnDestroy吗?可能如果您的类没有使用OnDestroy实现,那么ngOnDestroy()将不会被执行。这是the official linkOnDestroy

以下代码段显示了组件如何实现此接口以定义自己的自定义清理方法。

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnDestroy {
    ngOnDestroy() {
       // ...
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.