[英]using RxJs forkJoin to merge multiple api calls into single output array
[英]Using RxJS ForkJoin to combine results from multiple API calls
我正在嘗試使用 RxJS forkJoin 來組合 2 個 api 調用(理想情況下,我會及時添加更多)。 我正在使用 RxJs 6。
我有兩個接口。 一個接口IMyWrapperObj
包含另一個接口IData
的數組。
export interface IMyWrapperObj {
status: {
id: number;
prop: string;
anotherProp: string;
}
data: Data[]
}
export interface IData {
prop1: string;
prop 2: string;
}
我有一個調用第三方 api 的服務。 這個API的設置方式,我需要用不同的參數調用它兩次,並結合Angular端的結果。
getSomeDataFromAPI(param1, param2): Observable<IMyWrapperObj> {/// some code here}
現在,在組件中,我已經將服務注入到構造函數中,並且在 ngOnInit 中,我打算使用 forkJoin 進行 2 個 api 調用並將 output 組合成一個結果。
這是該代碼:
forkJoin({
request1: this.dataService.getSomeDataFromAPI('Astronomy', this.query.term),
request2: this.dataService.getSomeDataFromAPI('History', this.query.term)
}).subscribe(val => console.log(val));
我無法解決的錯誤(編譯時)是:
Observable 不可分配給 ObservableInput 類型。 Object 實際上是我唯一指定的已知屬性。
對此有什么想法嗎? 我一直無法消化一個明確的答案。
基於 forkJoin 的文檔
我認為訂閱fork join的方式有誤
forkJoin({ request1: this.dataService.getSomeDataFromAPI('Astronomy', this.query.term), request2: this.dataService.getSomeDataFromAPI('History', this.query.term) }).subscribe(({request1,request2}) => { console.log(request1); console.log(request2); });
我使用 forkjoin 的常用方法是使用數組及其索引
service.ts:-
getSomeDataFromAPI(Requests:Array<any>): Any {
//create a request observable batch array
let observableBatch = [];
//inside the array push each http request observable
Requests.forEach((request)=>{
observableBatch.push(
//service call
this._http
.post<IMyWrapperObj>(Url, {
requestbodyParam1: request.param1,
requestbodyParam2: request.param2
})
.pipe(
//catcherror block http
)
); //push end
});
//use forkJoin
return forkJoin(observableBatch);
}
組件.ts:-
//使用foreach或map或任何方式重寫下面的代碼,或者根據需要使用接口包裝器
let requests:Array<any>=[{'Astronomy', this.query.term},{'History', this.query.term}];
this.dataService.getSomeDataFromAPI(requests:Array)
.susbcribe((response:Any[])=>{
console.log(response[0]);//astronomy response
console.log(response[1]); //history response
},{error}=>{
//error block
});
https://www.learnrxjs.io/learn-rxjs/operators/combination/forkjoin
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.