2017-11-11 134 views
0

我正在關注here中的文檔。 我可以將數據傳遞給對話框,但我沒有從中獲取數據。 我在.afterClose()。subscribe()上取得未定義的結果。 我錯過了什麼?我猜在對話框的模板中有一些我需要做的事情,但上面的文檔沒有提供一個例子。 這裏是我的代碼:如何從MatDialog獲取數據?

import {Component, Inject, OnInit} from '@angular/core'; 
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material'; 

import {MySavior} from '../shared/my-savior'; 
import {Savior} from '../../savior/shared/savior'; 
import {SaviorDataService} from '../../savior/shared/savior-data.service'; 

@Component({ 
    selector: 'app-my-room-savior-select-dialog', 
    template: 'my data name: {{data.name}}' 
}) 
export class MySaviorSelectDialogComponent { 
    constructor(public dialogRef: MatDialogRef<MySaviorSelectDialogComponent>, 
    @Inject(MAT_DIALOG_DATA) public data: any) {} 

    onClose(): void { 
    this.dialogRef.close(); 
    } 
} 


@Component({ 
    selector: 'app-my-room-my-savior', 
    templateUrl: './my-savior.component.html', 
    styleUrls: ['./my-savior.component.css'] 
}) 
export class MySaviorComponent implements OnInit { 

    saviors: Savior[] = []; 
    mySaviors: MySavior[] = []; 

    constructor(private saviorDataServ: SaviorDataService, public dialog: MatDialog) {} 

    ngOnInit() { 
    ... 
    } 

    openSelectDialog(): void { 
    const dialogRef = this.dialog.open(MySaviorSelectDialogComponent, {data: {name: 'test'}}); 
    dialogRef.afterClosed().subscribe(result => { 
     console.log('result ' + result); //i got result undefined 
    }); 
    } 

} 

回答

1

我搞清楚後,我發現,我們可以通過對MatDialogRef.close數據()。

onClose(): void { 
    this.dialogRef.close('pass data here'); 
} 

該文檔僅提供onNoClick()函數,偶爾不需要傳遞任何數據。 onOkClick(),另一方面,我認爲應該或多或少像上面的onClose()。我不知道他們爲什麼不把它包含在文檔中。