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