【问题标题】:is it really necessary to destroy dynamic components?真的有必要销毁动态组件吗?
【发布时间】:2020-06-08 13:18:22
【问题描述】:
const validReportTemplates = {
  default: DefaultTemplateComponent
}

@ViewChild('container', { read: ViewContainerRef }) containerRef: ViewContainerRef;
  private _componentRef: ComponentRef<any>;

  constructor(
    public activeModal: NgbActiveModal,
    private _notificationsService: NotificationsService,
    private _componentFactoryResolver: ComponentFactoryResolver,
    private _inspectionService: InspectionService,
    private _reportService: ReportService
  ) {}

  ngAfterViewInit (): void {
    this._loadReportTemplate();
  }

  private _loadReportTemplate() {
    const inspection: Inspection = this._inspectionService.inspectionForm.value;
    this.containerRef.clear();
    const factory = this._componentFactoryResolver.resolveComponentFactory<any>(validReportTemplates['default']);
    this._componentRef = this.containerRef.createComponent(factory);

  }

  ngOnDestroy(): void {
    this._componentRef.destroy();
    this.containerRef.clear();
  }
}

DefaultTemplateComponent 中的 ngOnDestroy() 生命周期钩子无论如何都会被触发。如果我在父母 onDestroy 钩子中调用 destroy() 和 clear() 并不重要。那么真的有必要手动执行吗?

另一个有趣的事实是,当在 ngOnDestroy 钩子中注册超时时,对动态加载的组件的引用在销毁后存在。有什么想法吗?

ngOnDestroy(): void {
  this._componentRef.destroy();
  this.containerRef.clear();
  setTimeout(() => console.log(this._componentRef), 3000); // shows that DefaultTemplateComponent still exists
}

【问题讨论】:

  • 没有。正如您所说,当从 DOM 中删除元素时,angular 会为您完成工作并销毁所有组件。您需要做的是在ngOnDestroy() 期间取消订阅任何自定义可观察对象,否则可能导致内存泄漏。
  • @MikeS。谢谢你给的信息。但是为什么超时时仍然引用了已经销毁的组件呢?

标签: angular


【解决方案1】:

ngOnDestroy 对于清理组件中使用的数据结构/指针很有用。例如,假设您在 init 上为许多 observables 创建了 rxjs 订阅者。销毁不会清理它们,它们会一直存在,如果订阅处理程序期望对组件进行更改(更新状态、更改文本、计算某些值等),这将导致问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-19
    • 2021-04-26
    • 2021-11-08
    • 2018-12-17
    • 1970-01-01
    • 2013-12-01
    • 2018-04-05
    • 2021-01-25
    相关资源
    最近更新 更多