javascript - ngDestroy 生命周期不在动态创建的 Angular 组件中触发

标签 javascript angular angular7 angular8

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

在我动态创建的组件中,我从 API 获取一些数据,并使用 setInterval 方法定期每 5 分钟获取一次数据。我正在清除 ngDestroy 方法中的 Interval 实例,同时重定向到不同的页面,组件的 ngDestroy 没有触发,即使组件不在 View 中,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 ....
  }
}

最佳答案

需要手动销毁动态加载的组件: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

关于javascript - ngDestroy 生命周期不在动态创建的 Angular 组件中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60336333/

相关文章:

javascript - 在某些字段上禁用 Dojo 验证

javascript - 如何检测点击javascript上的每个 "this"

javascript - 一次只影响一个 Div - 不工作

css - 通过属性指令将 CSS 样式传递给子 HTML 元素

angular - 更改手机的日期时间后按钮无响应

html - Angular 7 不呈现 Bootstrap 控制

javascript - ASP.NET 未从 LinkBut​​ton onClick 获取 CommandArgument 值(VB)

angular - 我应该使用两个组件来编辑和创建 Angular 形式吗?

azure - npm 错误! 404 未找到 : har-validator@5. 1.2

angular - ngrx/store@6.1.0 在升级到 angular 7 时需要 @angular/core@^6.0.0 的对等体