[英]How to wait for a observable method to finish before proceeding in Angular 2
我是 Angular 的新手,我正在努力修復用 Angular 2 編寫的東西。在該方法中,我們調用了可觀察方法,之后我們為變量賦值。 在分配值之前,我需要 obersavable 方法來完成執行。 下面給出的代碼供您參考。
Method1(): void {
this.Service.getData()
.subscribe(
res => {
},
error => this.errorMessage = <any>error);
this.gotData = true;
}
因此,如上所示,我需要在 getData Observable 方法執行完畢后將 true 分配給 gotData 變量。 但是在我們實際獲取數據之前,gotData 就被賦值為 true。
請幫助我等到可觀察方法完成執行。 謝謝 !
聽起來你需要閱讀 Observables 和 Subscriptions。 Angular文檔
或者,subscribe() 方法可以在行中接受回調 function 定義,用於下一個、錯誤和完成處理程序。 例如,以下 subscribe() 調用與指定預定義觀察者的調用相同:
在您的情況下,您命名為res
的回調將在您的可觀察方法完成后被調用。
所以你的代碼可能是:
Method1(): void {
this.Service.getData()
.subscribe(
res => {
this.gotData = true;
},
error => this.errorMessage = <any>error
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.