【问题标题】:Do you need to unsubscribe from a subscription to router params in Angular?您是否需要取消订阅 Angular 中的路由器参数?
【发布时间】:2020-12-07 17:29:02
【问题描述】:

订阅组件中的查询参数时,需要退订吗?我正在努力避免内存泄漏。

订阅unsubscribe()的变量

  subscription$: Subscription

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.subscription$ = this.route.queryParams.subscribe(
      (params: any): void => {
        // ... Do stuff here ...
      }
    )
  }

  ngOnDestroy() {
    if (this.subscription$ !== undefined || this.subscription$ !== null) {
      this.subscription$.unsubscribe()
    }
  }

unsubscribe() 的无变量订阅


  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.queryParams.subscribe(
      (params: any): void => {
        // ... Do stuff here ...
      }
    )
  }

哪个是更好的解决方案?

【问题讨论】:

标签: angular typescript angular-router angular2-observables rxjs-observables


【解决方案1】:

ActivatedRoute 在组件被销毁时取消其所有订阅者的订阅。

您可以查看文档:https://angular.io/guide/router#!#reuse

当订阅组件中的 observable 时,您几乎总是 安排在组件被销毁时取消订阅。

有一些特殊的 observables 是不必要的。 ActivatedRoute 可观察对象属于例外。

ActivatedRoute 及其 observables 与 Router 隔离 本身。当路由组件不再存在时,路由器会销毁它 需要,注入的 ActivatedRoute 也随之消亡。

【讨论】:

    【解决方案2】:

    你可以找到这个问题以供参考

    Angular is it necessary to unsubscribe from this.activatedRoute subscriptions

    但我会说,只要您订阅了某些内容,就取消订阅始终是一个好习惯。它们有多种取消订阅的方法,我们只需使用一个额外的订阅变量即可做到这一点

    在这种情况下我也总是喜欢退订

    【讨论】:

      猜你喜欢
      • 2018-07-23
      • 2017-05-12
      • 2023-04-09
      • 2019-01-31
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多