DEV Community

Discussion on: When a service got destroyed in angular

Collapse
 
hp13055 profile image
F.1.armchair.expert • Edited

Your statement that nothing canbe found on the lifecycle hooks page is wrong.
angular.io/guide/lifecycle-hooks#o...
There it is! It says

"OnDestroy()
Put cleanup logic in ngOnDestroy(), the logic that must run before Angular destroys the directive.

This is the time to notify another part of the application that the component is going away.

This is the place to free resources that won't be garbage collected automatically. Unsubscribe from Observables and DOM events. Stop interval timers. Unregister all callbacks that this directive registered with global or application services. You risk memory leaks if you neglect to do so."

Collapse
 
hp13055 profile image
F.1.armchair.expert • Edited

@Bo
Your conclusion is wrong.
ngOnDestroy is fired BEFORE the directive gets destroyed. As you can read above, its supposed to be used to clean up resources. Nonetheless the directive may not get destroyed for some reason (for example because a reference is holding up to it). But still : it's working as intended => the event is fired because the component is supposed(!) to fade away.

Collapse
 
bo profile image
Bo Vandersteene

My articles is about services so providers and not directives. So the conclusion is for using ngOnDestroy on a service and NOT on a directive

Thread Thread
 
hp13055 profile image
F.1.armchair.expert • Edited

I've read the article again. You open it with
"If we read the OnDestroy lifecycle hook api description Angular OnDestroy we can use it on services."
But, how do you came to that conclusion? The lifecycle is described for components and directives. Where do you read it could be used on sercices?
You may have misunderstood whats written for onDestroy(). Services are mentioned there, right, but its meant as example to use onDestroy on your component to unregister it from(!) services.

Collapse
 
bo profile image
Bo Vandersteene

Yes for a directive the documentation is complete, but what if you're service got destroyed? a service is not the same as a directive IMHO. So please read the article again and don't think about a directive but think about a service.