我应该退订Angular Form更改吗?

时间:2018-06-26 14:46:28

标签: javascript angular observable ngrx

使用Angular Abstract Control订阅valueChanges中的更改时,是否有必要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 个答案:

答案 0 :(得分:0)

是的,但是有必要,但是您可以使用take直到。

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

相关问题