我們需要從 ngOnInit() 中一一呼叫多個 REST API。在呼叫第一個之后,我們需要在第二個 API 呼叫中傳遞這個回應,對于第三個,我們需要從第二個 API 呼叫中獲取值并將其傳遞給第三個。
但是在像下面這樣呼叫時,我們總是得到 undefined value 。
this.globalVar1 : any;
this.globalVar2 : any;
this.globalVar3 : any;
async ngOnInit() {
this.apiService.getFirstAPICall(request).subscribe(info => {
this.globalVar1 = info; //here value is coming from API service call
}
console.log(this.globalVar1); //here undefined
//Now calling the second API ** here we need this first variable
//but due to undefined we are getting error
this.apiService.getSecondAPICall(request.globalVar1).subscribe(info => {
this.globalVar2 = info;
}
console.log(this.globalVar2); //here undefined
uj5u.com熱心網友回復:
您正在運行異步代碼,這意味著您的請求可以并行執行,然后碰巧您在第一個請求的結果出現之前發出了第二個請求。
有幾種方法可以讓您的代碼按順序運行,一種是使用await關鍵字。這會等待當前行中的代碼完成,然后再執行下一行。
您的代碼將如下所示:
this.globalVar1 : any;
this.globalVar2 : any;
this.globalVar3 : any;
async ngOnInit() {
this.globalVar1 = await this.apiService.getFirstAPICall(request);
console.log(this.globalVar1);
this.globalVar2 = await this.apiService.getSecondAPICall(this.globalVar1);
console.log(this.globalVar2);
}
解決問題的另一種方法是在第一個請求的訂閱中發出第二個請求。
uj5u.com熱心網友回復:
訂閱是異步的,這意味著它不會等到執行來觸發下一行代碼。相反,您應該將您的.subscribe()轉化為承諾。通常使用.toPromise().
然后,您可以await根據承諾并將值分配給您可以傳遞給下一次執行的引數。
例子
async ngOnInit() {
const res1 = await this.apiService.getData(); // getData() should already be a promise returning a value of type Promise<YourType>
const res2 = await this.apiService.getData2(res1);
// etc...
}
uj5u.com熱心網友回復:
您可以使用 rxjs switchMap運算子,然后您可以將第一次呼叫中的資料傳遞給內部 observable(第二次呼叫)。你不需要任何全域變數,也不需要轉換為承諾,因為 httpClient 回傳一個 Observable
import { switchMap } from 'rxjs/operators';
...
this.apiService.getFirstAPICall(request).pipe(
map(response1 => // edit your data here)
switchMap((editedResponse1) => this.getSecondAPICall(editedResponse1) )
).subscribe()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/367284.html
下一篇:從Angular的串列中洗掉專案
