Alex Lomia
Alex Lomia

Reputation: 7235

Are services also destroyed when the component providing them gets destroyed?

Suppose we have the following code:

@Component(
    // ..
    providers: [SomeService]
)
export class SomeComponent {
    constructor(someService: SomeService) {}
}

Will the someService instance be destroyed whenever SomeComponent is destroyed? Or should one manually destroy it through onDestroy() hook?

Upvotes: 0

Views: 4155

Answers (2)

Estus Flask
Estus Flask

Reputation: 222538

As explained in this answer, providers follow the lifecycle and can have OnDestroy hook. They are destroyed when their injectors are destroyed.

If a provider belongs to component injector, it's destroyed with a component.

If a provider belongs to root injector, it's destroyed with an application.

Upvotes: 1

Robin Dijkhof
Robin Dijkhof

Reputation: 19288

Yes they do, check out this example

You can check yourself with the ngOnDestroy hook in your service:

class SomeService{
  ngOnDestroy() {
    console.log('Service destroy')
  }
}

Upvotes: 3

Related Questions