How to Unsubscribe
Various ways to Unsubscribe
Use Async Pipe: Use Async pipe to subscribe to an observable, it automatically cleans up, when we destroy the component.
Use Unsubscribe(): Use Unsubscribe() method on the subscription. It will clean up all listeners and frees up the memory
To do that, first create a variable to store the subscription.
obs: Subscription;
Assign the subscription to the obs variable
this.obs = this.src.subscribe(value => {
console.log("Received " + this.id);
});
Call the unsubscribe() method in the ngOnDestroy method.
ngOnDestroy() {
this.obs.unsubscribe();
}
When we destroy the component, the observable is unsubscribed and cleaned up.
0 comments:
Post a Comment