首页 > 解决方案 > 取消订阅 Rxjs Observables

问题描述

我开始使用一个使用 Rxjs observables 的遗留 angular 6 应用程序。组件中的可观察对象似乎没有使用我所看到的取消订阅。ngOnInit 中的订阅示例:

this.service.getCustomerDetail(customers).subscribe(
          (data) => {
            this.customerData = data;
          },
          () => {
            this.notify.addNotification(
              new notification(
                `Error retrieving customer data`
              )
            );
          }
        );

订阅者正在使用完成,即使其中没​​有任何内容,即 Rxjs 订阅的 Next、Error、Complete 值,但在我看来,它需要将这些推送到订阅中,然后在 ngOnDestroy 上取消订阅所有这些。即使完整在可观察范围内,这些没有取消订阅的订阅也会留在堆内存中,也就是导致内存泄漏,这是正确的吗?

在我的订阅使用错误和完整部分的情况下,我会使用 TakeUntil 方法,例如:

this.service.getCustomerDetail(customers)
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe(
          (data) => {
            this.customerData = data;
          },
          () => {
            //error section
            this.notify.addNotification(
              new notification(
                `Error retrieving customer data`
              )
            );
          },
          () => {
            //complete section
            this.loadAddlDetail();
          }
        );

感谢您提供有关此的任何信息。

标签: angularrxjs

解决方案


有两种方法可以做到这一点。如果这是一个孤立的案例,以下就足够了

方法 1 - 如果这是一个孤立的案例

-------------------------------------------------- -

在班上

更改类声明以包括OnDestroy

export class AppComponent implements OnInit, OnDestroy

添加私有变量来存储订阅

private serviceSubscription  = null

在 ngOnInit

this.serviceSubscription = this.service.getCustomerDetail(customers).subscribe(
      (data) => {
        this.customerData = data;
      },
      () => {
        this.notify.addNotification(
          new notification(
            `Error retrieving customer data`
          )
        );
      }
    );

实施 OnDestroy

ngOnDestroy() {
   if (this.serviceSubscription != null) {
     this.serviceSubscription.unsubscribe()
   }
} 

-------------------------------------------------- --------

方法 2 - 如果在多个地方看到这种情况

-------------------------------------------------- --------

为组件创建基类component-base.ts

import { Subscription } from 'rxjs';
import { OnDestroy } from '@angular/core';

export class ComponentBase implements OnDestroy {
    private subscriptions: Subscription[] = [];

    protected rxs(s: Subscription): void {
        this.subscriptions.push(s);
    }

    ngOnDestroy() {
        this.subscriptions.forEach(x => x.unsubscribe());
    }
}

将组件从ComponentBase

export class AppComponent extends ComponentBase implements OnInit

在 ngOnInit

ngOnInit() {
    this.rxs(this.service.getCustomerDetail(customers).subscribe(
        (data) => {
        this.customerData = data;
        },
        () => {
        this.notify.addNotification(
            new notification(
            `Error retrieving customer data`
            )
        );
        }
    ));
}

推荐阅读