Reputation: 785
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
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
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
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
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