NgOnDestroy doesn’t get called?

#ng_gotchas 1

Georgi Parlakov
ng-gotchas
Published in
2 min readFeb 11, 2018

#ng-gotchas

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.

Service implementing on destroy getting provided and injected. Straightforward angular.

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.

Workaround. Destroy from component.

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.

If provided inside of a component’s providers the service gets ngOnDestroy-ed.

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' providers
  • AppModule 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.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

ng-gotchas
ng-gotchas

Published in ng-gotchas

I had more than one "Oh angular gotcha!" moments and I want to share them.

Georgi Parlakov
Georgi Parlakov

Written by Georgi Parlakov

Angular and DotNet dev. RxJs explorer. Testing proponent. A dad. Educative.io course author. https://gparlakov.github.io/

Responses (2)

What are your thoughts?

What’s the advantage to having a Service as opposed to a plain old JavaScript object if you’re going to destroy it each time the component that instantiates it is destroyed?

Nice one! Thanks for sharing!

Recommended from Medium

Lists

See more recommendations