Search code examples
angularobservableangular-lifecycle-hooks

When gets a service destroyed that was injected into a dialog?


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


Solution

  • 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.