[英]Angular 12 How To Call Multiple Rest API Using Subscribe Method
我們需要從 ngOnInit() 中調用多個 REST API 一個一個。 調用第一個后,我們需要在第二個 API 調用中傳遞此響應,對於第三個調用相同,我們需要從第二個 API 調用中獲取值並將其傳遞給第三個。
但是在像下面這樣調用時,我們總是得到未定義的值。
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
您正在運行異步代碼,這意味着您的請求可以並行執行,然后您會在第一個請求的結果出現之前發出第二個請求。
有幾種方法可以讓您的代碼按順序運行,一種是使用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);
}
解決問題的另一種方法是在第一個訂閱中發出第二個請求。
訂閱是異步的,這意味着它不會等到它執行才能觸發下一行代碼。 相反,您應該將.subscribe()
轉換為 promise。 通常使用.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...
}
您可以使用 rxjs switchMap運算符,然后可以將數據從第一次調用傳遞到內部 observable(第二次調用)。 你不需要任何全局變量,也不需要轉換為 promise 因為 httpClient 返回一個 Observable
import { switchMap } from 'rxjs/operators';
...
this.apiService.getFirstAPICall(request).pipe(
map(response1 => // edit your data here)
switchMap((editedResponse1) => this.getSecondAPICall(editedResponse1) )
).subscribe()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.