2017-09-16 85 views
3

是否有合适的方式销毁由对话框创建的组件实例? 当我关闭对话框 - 组件实例不设置:角度材质销毁对话框实例

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()方法。

回答

1

你应该关心自己处置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

+0

是的,具有超时的实际实施是误导性的。在角度对话框关闭后,组件即被销毁。就我而言,当组件被销毁时,我只是不得不退出观察对象。 – Brivvirs

0

我处理我的对话接近这样了。只需将打开的对话框引用设置为空。

let ordersDialog = this.dialog.open(BasketDialogComponent, { 
    data: product 
}); 
ordersDialog.afterClosed().subscribe(x => { 
    ordersDialog = null; 
}); 
+0

你可以在这里试试https://plnkr.co/edit/7Z3HCDJZFh4KEIG8gq9n?p=preview对话框关闭后,定时器仍然呈现 – yurzui