2017-02-14 38 views
2

我有一個對話框,選擇yes和no選項(確認框)。我想等到用戶按下對話框中的yes或no按鈕,但現在單擊按鈕時,即使在單擊對話框中的選項之前,控制檯日誌也會打印初始/空字符串。MD對話框材料Angular 2等待關閉

HTML:

<button (click)="foo()"></button> 

組件:

selectedOption = ''; 

foo() { 
    this.openDialog(); 
    console.log('selectedOption: ' + this.selectedOption); // Prints initial Value 
    // hit the API if selectedOption is yes. 
} 

openDialog() { 
    dialogRef.afterClosed().subscribe(result => { 
    this.selectedOption = result; 
    }); 
} 

回答

1

它與你寫的代碼的方法和afterClosed返回可觀察到的異步的事實做。 後 this.openDialog(); 您呼叫 console.log(....); 此時selectedOption通話仍然是空的,因爲你在上面爲空字符串初始化它。

只需推動的console.log和API邏輯到所述訂閱塊:

selectedOption = ''; 

foo() { 
    this.openDialog(); 
} 

openDialog() { 
    dialogRef.afterClosed().subscribe(result => { 
    this.selectedOption = result; 
    console.log('selectedOption: ' + this.selectedOption); // Prints 
    // hit the API if selectedOption is yes. 
    }); 
}