Reputation: 7235
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
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
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