starlight
starlight

Reputation: 785

How to unsubscribe from valueChanges in Angular 4 reactive forms?

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.

Upvotes: 7

Views: 10148

Answers (4)

Radu Linu
Radu Linu

Reputation: 1261

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.

Upvotes: 0

Vitalii Polulikh
Vitalii Polulikh

Reputation: 69

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

Upvotes: 5

Venomy
Venomy

Reputation: 2244

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

Upvotes: 7

Suren Srapyan
Suren Srapyan

Reputation: 68635

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

Upvotes: 14

Related Questions