是否有正确的方法来销毁由对话框创建的组件实例。 当我关闭对话框组件实例时没有处理:
import { Component, OnInit, Input, Output, EventEmitter, Inject } from '@angular/core';
import { MdDialog, MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
@Component({
selector: 'basket',
templateUrl: './basket.component.html',
styleUrls: ['./basket.component.css']
})
export class BasketComponent implements OnInit {
@Input() Product: any;
}
@Component({
selector: 'basket-dialog',
template: '<div><basket [Product]="Product"></basket></div>'
})
export class BasketDialogComponent implements OnInit {
Product: any;
constructor(public dialogRef: MdDialogRef<BasketComponent>,
@Inject(MD_DIALOG_DATA) public productData: any) { }
ngOnInit() {
this.Product = this.productData;
this.say();
}
say() {
setTimeout(() => this.say(), 1000);
console.log('test');
}
}
创建对话框:
let ordersDialog = this.dialog.open(BasketDialogComponent, {
data: product
});
ordersDialog.afterClosed().subscribe(x => {
// something like: orderDialog.componentInstance.dispose();
});
即使关闭对话框后,say()
方法仍在执行。
答案 0 :(得分:2)
你应该关心自己处理setTimeout
:
export class BasketDialogComponent implements OnInit, OnDestroy {
timeoutId;
say() {
this.timeoutId = setTimeout(() => this.say(), 1000);
console.log('test');
}
ngOnDestroy() {
if (this.timeoutId) {
clearTimeout(this.timeoutId);
}
}
}
<强> Plunker Example 强>
答案 1 :(得分:0)
我这样关闭后放置对话框。只需将打开的对话框引用设置为null。
let ordersDialog = this.dialog.open(BasketDialogComponent, {
data: product
});
ordersDialog.afterClosed().subscribe(x => {
ordersDialog = null;
});