HelloComponent gets a SampleService instance, defining a Service Provider.
When HelloCompoment is destroyed, I don't understand why SampleService survives.
If HelloComponent got a SampleService instance by type (avoiding ServiceProvider), no problem occurs.
sample-service.ts
@Injectable()
export class SampleService implements OnDestroy{
constructor(){
console.log('created new sample service');
}
ngOnDestroy(){
console.log('destroyed sample service');
}
}
hello-component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'
import { SampleService } from '../service/sample.service'
let ServiceFactory = () => {
console.log('Providing new SampleService');
return new SampleService();
};
let ServiceProvider = {
provide: SampleService,
useFactory: ServiceFactory
};
@Component({
selector: 'hello',
templateUrl: './hello.component.html',
providers: [ServiceProvider]
})
export class HelloComponent implements OnInit, OnDestroy {
constructor(private sampleService: SampleService){}
ngOnInit(){
console.log("Hello component created!")
}
ngOnDestroy(){
console.log("Hello component destroyed!")
}
}
Here stackblitz: https://stackblitz.com/edit/angular-vkhmma (click on toggleHello and see console logs)
How could I force the service destroying when component ends?
This is a known issue in Angular, but one that is (unfortunately) by design.
The presence of an OnDestroy callback hook is checked at compile time and since your ServiceProvider is wrapping a Factory which creates a SampleService, the Angular compiler unfortunately has no idea that this hook even exists, so it will never be called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With