[英]combining results from multiple rxjs observables
我有一個自動完成輸入,當用戶輸入時,它從多個端點獲取數據,例如:
//service call to fetch data and return as single observable
getAutocompleteSuggestions() {
const subs$ = [
this.http.get(endpoint1),
this.http.get(endpoint2),
this.http.get(endpoint3)
];
return Observable.forkJoin(...subs$);
}
每個端點都返回以下形式的數據:
{ data: [], status: xyz }
我想使用switchmap,因為我只想顯示最終調用的結果,並嘗試了以下內容:
this.getAutocompleteSuggestions(query)
.switchMap(res => {
return res.data;
})
.subscribe((results: any) => {
this.results = results;
});
但是switchmap中的'res'是一個數組,任何想法結果如何包含一個包含任意數量的observable響應數據的單個數組?
我不完全明白你想要什么,但我認為這是:
$filter: Subject<string> = new Subject(); //I guess we have some value to filter by??
將值推送到主題:
this.$filter.next(myNewValue);
在構造函數或init中:
this.$filter
.switchMap(filterValue => { //Get the values when filter changes
subs$ = [
this.http.get(endpoint1 + filterValue),
this.http.get(endpoint2 + filterValue),
this.http.get(endpoint3 + filterValue)
];
return Observable.forkJoin(...subs$);
})
.map(results => { //now map you array which contains the results
let finalResult = [];
results.forEach(result => {
finalResult = finalResult.concat(result.data)
})
return final;
})
.subscribe(); //Do with it what you want
當我們為我們的主題添加一個新值時,整個蒸汽將再次執行。 如果有的話,SwitchMap將取消所有就緒請求。
我使用了類似的東西,到目前為止運作良好:
let endpoint1 = this.http.get(endpoint1);
let endpoint2 = this.http.get(endpoint2);
let endpoint3 = this.http.get(endpoint3);
forkJoin([endpoint1, endpoint2, endpoint3])
.subscribe(
results => {
const endpoint1Result = results[0].map(data => data);
const endpoint2Result = results[1].map(data => data);
const endpoint3Result = results[2].map(data => data);
this.results = [...endpoint1Result, ...endpoint2Result, ...endpoint3Result];
},
error => {
console.error(error);
}
);
顯然這是一個非常簡單的例子,您將能夠更好地處理結果以滿足您的需求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.