2017-02-14 74 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. 
    }); 
}