-1

I wrote a service and injected it into my dialog. I expected the service's ngOnDestroy() function to be called when I close the dialog. But it doesn't.

So I wondering when ngOnDestroy() will be fired?
How would I unsubscribe my Subscriptions in the service if I want them to be killed as the dialog closes?

Here is the stackblitz example: https://stackblitz.com/edit/angular-bf1taz

coconut
  • 494
  • 2
  • 5
  • 13
  • I do believe that `ngOnDestroy` lifecycle hook is only for components and wont work on service, even if you can implement the interface. – Majesty Oct 25 '19 at 12:11
  • It says in the documentation: https://angular.io/api/core/OnDestroy - "A lifecycle hook that is called when a directive, pipe, or service is destroyed" – coconut Oct 25 '19 at 12:12
  • oh you are right, so here is the answer then https://stackoverflow.com/questions/45898948/angular-4-ngondestroy-in-service-destroy-observable. You should put your service into the component providers, then it will be destroyed along with component, if it is in root providers, then it will be destroyed when the root component is – Majesty Oct 25 '19 at 12:14

1 Answers1

2

Since you provided your Service in your app.module.ts in the "services" array, your Service would be a global instance for all of your components. This is very often wanted since you often use Service to store and communicate data between components and do not want to loose those whenever a component that uses it is destroyed.

If you want to have different instances of your service (only use very cautiously) you would need to limit your providers.

Reference the docs for info.

If you want to reset your Service, you could have for example have something like a reset function in your service, which manually cleans up after you and is called onClose of your dialog.

Chund
  • 355
  • 2
  • 15