Angular Material销毁对话框实例

Bri*_*irs 6 angular-material2 angular

是否有适当的方法来销毁由对话框创建的组件实例。当我关闭对话框组件实例不被处置时:

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

创建对话框:

let ordersDialog = this.dialog.open(BasketDialogComponent, {
    data: product
});
ordersDialog.afterClosed().subscribe(x => {
   // something like: orderDialog.componentInstance.dispose();
});
Run Code Online (Sandbox Code Playgroud)

say()即使关闭对话框,该方法仍在执行。

yur*_*zui 3

您应该关心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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

笨蛋的例子

  • 是的,超时的实际实现是有误导性的。角度对话框关闭后,组件立即被销毁。就我而言,当组件被销毁时,我只需取消订阅可观察对象。 (2认同)