2017-02-14 11 views
2

私はyesとnoオプション(確認ボックス)を持つダイアログを持っています。ユーザーがダイアログからはいまたはいいえボタンを押すまで待機したいが、ダイアログボックスのオプションをクリックする前であっても、今すぐボタンをクリックすると、コンソールログに初期/空文字列が印刷されます。MDダイアログの材質角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(); への呼び出しあなたはselectedOptionこの時点で console.log(....); を呼び出す後 は空のままです。

だけで購読ブロックには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. 
    }); 
} 
関連する問題