【问题标题】:Should I unsubscribe from Angular Form changes?我应该取消订阅 Angular 表单更改吗?
【发布时间】:2018-12-05 08:13:15
【问题描述】:

当使用valueChanges 订阅Angular Abstract Control 中的更改时,是否需要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 教程似乎强调了取消订阅以避免内存泄漏的重要性。

【问题讨论】:

  • 非常好的问题,我也这么想,1+ 点赞 :)

标签: javascript angular observable ngrx


【解决方案1】:

是的,这是必要的,但您可以使用 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

【讨论】:

  • 你能给我们一些参考吗?
猜你喜欢
  • 1970-01-01
  • 2021-07-22
  • 1970-01-01
  • 2020-02-05
  • 2019-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-30
相关资源
最近更新 更多