最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Should I unsubscribe from Angular Form changes? - Stack Overflow

programmeradmin0浏览0评论

When subscribing to changes in an Angular Abstract Control using valueChanges, is it necessary to unsubscribe()?

I often do this:

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

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

But should I be managing the subscription myself (as I do with ngrx in general)?:

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();
   }
}

The only reason I have not done this previously is because tutorials, examples and documentation on Angular Forms generally omit storing a reference to the subscription, and instead, just use valueChanges as is.

Conversely, ngrx tutorials seem to highlight the importance of unsubscribing to avoid memory leaks.

When subscribing to changes in an Angular Abstract Control using valueChanges, is it necessary to unsubscribe()?

I often do this:

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

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

But should I be managing the subscription myself (as I do with ngrx in general)?:

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();
   }
}

The only reason I have not done this previously is because tutorials, examples and documentation on Angular Forms generally omit storing a reference to the subscription, and instead, just use valueChanges as is.

Conversely, ngrx tutorials seem to highlight the importance of unsubscribing to avoid memory leaks.

Share Improve this question edited Jun 26, 2018 at 15:10 Jack asked Jun 26, 2018 at 14:46 JackJack 10.6k16 gold badges78 silver badges129 bronze badges 1
  • 1 Very good question, I was thinking the same, 1+ upvote from me :) – user6600549 Commented Mar 15, 2019 at 11:08
Add a ment  | 

1 Answer 1

Reset to default 7

Yes it is necessary, but you could use take until instead.

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$.plete();
}

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

发布评论

评论列表(0)

  1. 暂无评论