HelloComponent
获取一个SampleService
实例,定义一个服务提供者。
HelloCompoment
被销毁后,我不明白为什么SampleService
得以幸存。
如果HelloComponent
按类型有一个SampleService
实例(避免使用ServiceProvider
),则不会发生任何问题。
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!")
}
}
这里是堆叠闪电战:https://stackblitz.com/edit/angular-vkhmma (单击toggleHello,然后查看控制台日志)
在组件结束时如何强制服务销毁?