In my ngOnInit method I am subscribing to the Router like this:
this.router.events.subscribe(
event => {
if (event instanceof NavigationEnd) this.clearMessages();
}
);
Normally, for Observables outside of the HttpClient package I call unsubscribe in the ngOnDestroy method but when I tried that here I discovered that this.router.events does not have such a method. Am I mistaken or is there something different about this Observable? Why would unsubscribe not be implemented?
Generally you do not need to unsubscribe from HTTP calls. The ActivatedRoute and its observables are insulated from the Router itself so the Angular Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.
events. subscribe() if you console. log(sub) you will see it has the unsubscribe method.
No need to unsubscribe from internal observables of an application scoped service since this service never get's destroyed, unless your entire application get's destroyed, there is no real reason to unsubscribe from it and there is no chance of memory leaks.
Last but not least step is to trigger unsubscribe$ during the ngOnDestroy . We call . next() method to trigger new value emission and . complete() to automatically unsubscribe all the observers.
I discovered that this.router.events does not have such a method
You call unsubscribe
on subscriptions, not observables. And this.router.events
is an observable, not subscription. So the following would work:
const subscription = this.router.events.subscribe(...);
subscription.unsubscribe();
You are right, some observables need no manual unsubscription from, observables like:
first()
Similar information can be found on this reddit site also. This also means that no need to worry about memory leaks from observables in these classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With