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?