使用 rxjs 和 angular,是否有必要取消订阅在应用程序组件的 onInit 方法中仅发生一次的订阅? [英] with rxjs and angular, Is it necessary to unsubscribe for the subscriptions that happen only once in app component's onInit method?

查看:27
本文介绍了使用 rxjs 和 angular,是否有必要取消订阅在应用程序组件的 onInit 方法中仅发生一次的订阅?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于ngOnInit在app的生命周期中只被调用一次,当我在ngOnInit中订阅一个observable时,是否还需要取消订阅?

Since the ngOnInit is called only once in app's life, when I make a subscription to an observable in ngOnInit, is it still necessary to unsubscribe?

应用程序/标签页关闭后,应用程序是否有可能为浏览器造成内存泄漏?

Is it possible for the app to create memory leak for the browser after the app/tab is closed?

推荐答案

简短的答案是:

1) 总是

2) 是的

这篇文章 很好地描述了为什么我们应该取消订阅所有 observables,以及如何在 angular 中以有效的方式做到这一点.

This article describes very well why we should unsubscribe from all observables, and how to do it in an effective way in angular.

如果您订阅了 ngOnInit 函数,您应该通过 ngOnDestroy 取消订阅.

If you are Subscribing on the ngOnInit function you should be unsubscribing via ngOnDestroy.

我通常创建一个 unsubscribe 主题,然后在 ngOnDestroy 上调用 next() .我的所有订阅都带有 takeUntil(unsubscribe).

I usually create an unsubscribe Subject, and call next() on it on ngOnDestroy. I would have all my subscriptions with a takeUntil(unsubscribe).

这就是我的意思:

unsubscribe = new Subject();

(...)

subscribeTo() {
   this.myService.getAll().pipe(
      takeUntil(this.unsubscribe),
    ).subscribe(data => this.localData = data);
}


ngOnDestroy() {
    this.unsubscribe.next();
    this.unsubscribe.complete();
  }

这篇关于使用 rxjs 和 angular,是否有必要取消订阅在应用程序组件的 onInit 方法中仅发生一次的订阅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆