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 ....
}
}
您需要通过手动调用: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
}
}