NgOnDestroy doesn’t get called?
#ng_gotchas 1

Ever feel like angular got ya?
I do. This is the story of the first ever gotcha that angular got me with. It was in our angular 2 then brand new and fresh app. Right after 2 final.
I was coding components, using the life-cycle hooks. You know ngOnInit, ngOnDestroy… When the time came to have a service that needs to get destroyed when a component is destroyed I simply slapped “extends OnDestroy” on it, injected it in my component and continued on my path.
When later I realized that service was not getting destroyed I was taken by surprise and decided that OnDestroy does not get called on anything else than components or directives. Makes sense right?
My workaround was to have onDestroy methods and call them from the component on it’s destroy.
For the longest time I did not use OnDestroy on any services. Then a colleague of mine pointed out that services do get their ngOnDestroy called. As it turns out they do. But only when provided via components that get destroyed at some point by angular.
So there you have it — my first ever ng-gotcha and my take on working around it.
My take on that:
FeedComponent
provides the service and component does get destroyed and in turn it destroys its 'destructable' providersAppModule
provides the service but never gets destroyed by angular until user navigates away from our site at which point the Garbage collector is responsible for eventually cleaning that memory.
Head over to github for an example app. (I wanted to export that as a plunkr but — not yet possible).
There is an issue on angular discussing this topic.
PS.The service will NOT get destroyed if provided via a token in the component! See the branch.
PPS: A similar issue when using router to navigate async discussed here.