【问题标题】:ngDestroy lifecycle is not Triggering in dynamically created Angular componentngDestroy 生命周期未在动态创建的 Angular 组件中触发
【发布时间】:2020-06-05 17:55:06
【问题描述】:

ngDestroy 生命周期方法不会触发动态创建的组件。 我正在使用 ComponentFactoryResolver 动态创建多个组件。

在我动态创建的组件中,我从 API 获取一些数据,并使用 setInterval 方法每隔 5 分钟定期获取数据。我正在清除 ngDestroy 方法中的 Interval 实例,在重定向到不同页面时,组件的 ngDestroy 没有触发,即使组件不在视图中,API 也会触发。

这就是我动态创建组件的方式。

    const factory = this.resolver.resolveComponentFactory(DynamicComponent); // Component Construction
    const ref = factory.create(this.injector);

这是我的 DynamicComponent,它具有以下功能

import { Component, OnInit, OnDestroy } from "@angular/core";

@Component({
  selector: "app-dynamic,
  templateUrl: "./dynamic.component.html",
  styleUrls: ["./dynamic.component.scss"]
})
export class DynamicComponent implements OnInit, OnDestroy {
  loopCount: number;
  autoRefreshInterval: any;
  constructor() {}

  ngOnInit() {
    this.fetchData();
    this.startAutoRefreshLoop();
  }

  ngOnDestroy(): void {
    console.log("Destroying loop"); // ngOnDestroy is not triggering
    this.clearAutoRefreshLoop();
  }

  clearAutoRefreshLoop() {
    clearInterval(this.autoRefreshInterval);
  }

  /*
    function for starting the Automatically recall the service for certain period of time
  */
  startAutoRefreshLoop() {
    console.log("starting loop");
    this.loopCount = 10 * 1000;
    this.autoRefreshInterval = setInterval(() => {
      this.fetchData();
    }, this.loopCount);
  }

  fetchData() {
    // FETCHING DATA FROM API CODE ....
  }
}

【问题讨论】:

  • 你能在 StackBlitz 上创建一个最小的工作示例吗?

标签: javascript angular angular7 angular8


【解决方案1】:

需要手动销毁动态加载的组件:this.componentRef.destroy();触发ngOndestroy()

例子:

import {
    Component,
    ViewChild,
    ViewContainerRef,
    ComponentFactoryResolver,
    ComponentRef,
    ComponentFactory
} from '@angular/core';
import { DynamicComponent } from './dynamic.component';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent {
    title = 'app';
    componentRef: any;
    @ViewChild('container', { read: ViewContainerRef }) entry: ViewContainerRef;
    constructor(private resolver: ComponentFactoryResolver) { }
    createComponent(message) {
        this.entry.clear();
        const factory = this.resolver.resolveComponentFactory(DynamicComponent); 
        this.componentRef = this.entry.createComponent(factory);
    }
    destroyComponent() {
        this.componentRef.destroy(); // you need to call this
    }
}

欲了解更多信息:how-to-dynamically-create-a-component-in-angular

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-10
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 2012-03-30
    相关资源
    最近更新 更多