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,139
  • 11
  • 45
  • 83

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
  • 17,778
  • 11
  • 60
  • 104
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
  • 179,509
  • 61
  • 360
  • 499