2017-09-16 59 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