首页 > 解决方案 > 我应该取消订阅 Angular 表单更改吗?

问题描述

使用valueChanges订阅Angular 抽象控件中的更改时,是否有必要?unsubscribe()

我经常这样做:

// this.form is a FormGroup within a Component.

this.form.valueChanges.subscribe(_ => {
  console.log(this.form.value);
});

但是我应该自己管理订阅吗(就像我ngrx一般做的那样)?:

import { Subscription } from 'rxjs';

// this.subscription is ngrx Subscription.

this.subscription = this.form.valueChanges.subscribe(_ => {
      console.log(this.form.value);
});

public ngOnDestroy() {
  if (this.subscription) {
      this.subscription.unsubscribe();
   }
}

我之前没有这样做的唯一原因是,Angular Forms 上的教程、示例和文档通常会省略存储对订阅的引用,而是按原样使用valueChanges 。

相反,ngrx 教程似乎强调了取消订阅以避免内存泄漏的重要性。

标签: javascriptangularobservablengrx

解决方案


是的,这是必要的,但您可以使用 take until 代替。

private unsubscribe$: Subject<void> = new Subject<void>();

this.subscription = control.valueChanges
 pipe(takeUntil(this.unsubscribe$))
 .subscribe(_ => {
      console.log(this.form.value);
});

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

https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87


推荐阅读