Pedro Arantes
Pedro Arantes

Reputation: 5379

Angular services "lifecycle" in lazy loading

We know that Angular services do not have lifecycles as components have. My question is about 'destructing' a service when it has done.

In my application, there is a lazy module Module A which provides a service Service A when it is loaded (only Module A needs Service A). When done, I call another lazy module and Service A is no longer necessary, but it is kept by the Angular injector. Being more specific, Angular injector tree has now a single root injector and a child injector for Module A.

My question: as the service is kept running, should I create a function to destroy it (unsubscribe, clean arrays etc) and call it when Module A is being closed or there is another way to destroy it?

I've searched Angular Injector Class but it doesn't have some delete method to delete specific services.

Upvotes: 1

Views: 1122

Answers (1)

DeborahK
DeborahK

Reputation: 60518

If you register the service in a component, such as the primary component of Module A instead of in Module A directly, then the service will be destroyed when the component is destroyed.

Upvotes: 1

Related Questions