angular - 从服务创建后销毁组件实例
问题描述
我正在使用服务创建动态组件。组件已创建,但未ngOnDestroy
调用生命周期外观。
下面是我的服务文件代码。
@Injectable()
export class CreateComponentService implements OnDestroy {
private rootViewContainer: ViewContainerRef;
private componentFactory: ComponentFactory<any>;
private componentReference;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
setRootViewContainerRef(view: ViewContainerRef): void {
this.rootViewContainer = view;
}
createComponent(content, type) {
this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(type);
this.componentReference = this.rootViewContainer.createComponent(this.componentFactory);
this.componentReference.instance.contentOnCreate(content);
}
ngOnDestroy() {
// Destroy components to avoide memory leaks
this.componentReference.destroy();
}
}
在 Component.ts
constructor(private service: CreateComponentService) {}
data.forEach(response => {
this.service.createComponent(response, type);
});
请告诉我销毁组件实例的最佳方法
解决方案
您没有显式销毁服务,并且不会调用服务 onDestroy 方法。
您可以尝试从更改检测树中分离视图,这与您需要的类似,
private insertComponent(componentType): void {
const factory = this.factoryResolver.resolveComponentFactory(componentType);
var containerRef = this.rootViewContainer.createComponent(factory);
// always get the most recently appended node
var viewRef = this.rootViewContainer.get(this.rootViewContainer.length - 1);
viewRef.detach();
containerRef = null;
}
containerRef
最终将被垃圾收集。而且由于您分离了视图,它的行为就像静态内容一样。请注意,如果您 destroy containerRef
,关联的 view/html 也将被销毁。
推荐阅读
- python - 在 Python 中的 for 循环语句中创建一个循环
- python - 如何有条件地将一个数据帧中的值记录到另一个数据帧中?
- numbers - 查找给定自然数中是否有奇数的最快方法是什么
- python - 如何修复这个通过参数化函数列表迭代的“for”循环?
- r - 如何在R中获得摘要基分类
- powershell - 从 CSV 禁用/启用 AD 用户帐户
- mercurial - Tortoise 上的 Mercurial HG 卡住 - 等待锁定工作目录
- tsql - 如何在 SSIS 表达式的列中删除 2 个特殊字符之间的多个字符
- javascript - 如何根据新旧数据过滤数据
- laravel - 如何为 laravel 8 工厂设置参数?