0

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?

Alex Lomia
  • 6,705
  • 12
  • 53
  • 87

2 Answers2

3

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')
  }
}
Robin Dijkhof
  • 18,665
  • 11
  • 65
  • 116
1

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.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565