[英]Angular How to make subscribe wait for a call to finish
插入注:此問題與其他大多數與“如何從異步調用返回響應?”之類的問題不同。 因為它使用SUBSCRIBE。 據我了解,subscribe告訴它每當發生更改時就執行某項操作,因此您不能將代碼放入subscribe中,因為它只有在更改時才會運行(永遠為時已晚)。 僅當您了解Angular,Subscribe和HttpClient時,才回答。 現在我的原始問題是:
我有一個問題,我遍歷一個數組並對數組中的每個項目進行get調用。 我的問題是所有這些獲取請求都是異步發生的,這意味着它們都試圖在先前的獲取仍在接收其響應的同時獲取。 這會導致錯誤。 這是一個粗略的示例:
this.MyArray = [1, 2, 3, 4, 5];
this.MyArray.forEach(element => {
this.httpClient.get('http...')
.subscribe(
(response: any) => {
})
)}
我如何讓forEach循環在進入下一個項目之前等待呼叫響應? 我嘗試查看回復,但我聽不懂:(
您可以將數組映射到可觀察的流中。 然后,您可以使用concat
運算符連續執行可觀察對象。
import {
concat
} from 'rxjs/observable/concat';
this.MyArray = [1, 2, 3, 4, 5];
const observables: Observable<any>[] = this.myArray.map(() => this.httpClient.get('http...'));
concat(...observables).subscribe(resp => {
// handle responses, they will execute one after another,
// each waiting for the previous one to finish
})
嘗試這個
this.totalCount = this.MyArray.length;
this.i=1;
getData(){
let ob = this.MyArray[this.i-1];
this.httpClient.get('http...')
.subscribe(
(response: any) => {
this.i++;
if(this.i <= this.totalCount){
getData()
}
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.