【问题标题】:angular unsubscribe does not work without ngOnDestroy没有 ngOnDestroy,角度取消订阅不起作用
【发布时间】: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


【解决方案1】:

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

下面的 sn-p 展示了组件如何实现这个接口来定义自己的自定义清理方法。

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnDestroy {
    ngOnDestroy() {
       // ...
    }
}

【讨论】:

    猜你喜欢
    • 2018-11-22
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 2021-07-22
    • 2016-04-27
    • 2017-11-26
    相关资源
    最近更新 更多