How to unsubscribe from valueChanges in Angular 4 reactive forms?
Asked Answered
B

4

7

I am making a reactive form in Angular 4 and looking for valueChanges in the form like below:

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

The above code works perfectly. But how to unsubscribe from the valueChanges on ngOnDestroy() as this.searchForm.valueChanges.unsubscribe() doesn't seem to work. Please help me solve this.

Bornite answered 13/11, 2017 at 10:28 Comment(0)
C
14

subscribe returns an object of type Subscription from which you can unsubscribe

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

...

ngOnDestroy() {
   this.subscription.unsubscribe();
}
Concurrence answered 13/11, 2017 at 10:29 Comment(1)
This is the right solution. You have to check all subscriptions and ensure that you are unsubscribing from all of them.Marucci
A
7

@Suren has the right answer, I would just like to add some code I use when I have many subscriptions.

...
this.subscriptions.push(this.searchForm.valueChanges.subscribe((value) => {
   console.log(value);
}));
...

private subscriptions: Subscription[] = [];

ngOnDestroy(): void {
    this.subscriptions.forEach((sub) => {
        sub.unsubscribe();
    })
}
Alys answered 13/11, 2017 at 10:34 Comment(1)
I didn't realize that the subscribe method actually had a return value. This is great stuff !Wrung
B
5

I created Subscription disposer class

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

export class SubscriptionDisposer implements OnDestroy {
  protected ngUnsubscribe: Subject<void> = new Subject<void>();
  constructor() {
  }
   ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}

then you need to extend your component class by SubscriptionDisposer Your code will look like

this.searchForm.valueChanges
.takeUntil(this.ngUnsubscribe)
.subscribe((value) => {
   console.log(value);
});
Bonnell answered 24/2, 2018 at 13:25 Comment(1)
the syntax seems to be outdated. Now it should be: this.searchForm.valueChanges.pipe(takeUntil(this.ngUnsubscribe)).subscribe(...Ortegal
M
0

This post has the right solution. In a few cases is not working because there could be multiple subscriptions.

You have to check all subscriptions and ensure that you are unsubscribing from all of them.

Marucci answered 21/7, 2020 at 13:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.