angular - 使用 useFactory 提供服务时未触发 ngOnDestroy
问题描述
HelloComponent
获取一个SampleService
实例,定义一个服务提供者。什么时候HelloCompoment
被摧毁,我不明白为什么还SampleService
活着。
如果按类型获取实例(避免),则不会出现问题HelloComponent
。SampleService
ServiceProvider
示例服务.ts
@Injectable()
export class SampleService implements OnDestroy{
constructor(){
console.log('created new sample service');
}
ngOnDestroy(){
console.log('destroyed sample service');
}
}
你好-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!")
}
}
这里stackblitz:https ://stackblitz.com/edit/angular-vkhmma (点击toggleHello并查看控制台日志)
组件结束时如何强制服务销毁?
解决方案
这是Angular中的一个已知 问题,但(不幸的是)这是设计使然。
OnDestroy
回调钩子的存在是在编译时检查的,因为你ServiceProvider
包装了一个创建 的工厂,SampleService
不幸的是,Angular 编译器不知道这个钩子甚至存在,所以它永远不会被调用。
推荐阅读
- vuejs2 - Vue Bootstrap - 工具提示不适用于动态呈现的 HTML
- phpstorm - WebStorm 对 postcss-simple-vars 的支持
- javascript - 首先用 webpack 响应 js 应用程序。用java
- java - drawContours 不填充 / JAVA - OpenCV
- tidb - 每个 Region 的副本数是否可配置?如果是,如何配置?
- ios - IOS如何管理后台应用的内存?
- jquery - 浏览器控制台中的 ajax 错误 - 不是函数
- python - Python 使用字符串操作 a[start:end] 添加换行符
- java - 如何获取资源文件列表?
- ios - 使用 NSURLSessionConfiguration 进行 iOS 后台下载