Reputation: 11864
I want execute x requests in paralel and merge array Observavble of array in only one Observable of array with RXJS?
public getMetrics(url: string): Observable<GenericMetric[]> {
const ox: Observable<GenericMetric[]>[] = [];
res.forEach(elem => {
ox.push(this.http.get<GenericMetric[]>(url));
});
return forkJoin(...ox);
}
I try:
return forkJoin(...ox); // return array of GenericMetric[] but I want all results in GenericMetric[]
I looking for how to merge my array of array result in olny one array
return forkJoin(ox).pipe(?????);
EDIT:
I try:
return forkJoin(...ox).pipe(tap(d => console.log(d) ));
and my result is:
[
[{a:1}, {a:2}, {a:3}],
[{a:4}, {a:5}]
]
but I want :
[{a:1}, {a:2}, {a:3}, {a:4}, {a:5}]
Upvotes: 0
Views: 61
Reputation: 42526
This is a demo on how you can achieve the desired results. You can use ES6's spread syntax to flatten to array of arrays.
const arr = [
[{a:1}, {a:2}, {a:3}],
[{a:4}, {a:5}]
];
const res = [];
arr.map(item => {
res.push(...item)
})
console.log(res)
forkJoin(ox)
will return you an observable of type Observable<GenericMetric[]>[]
, which means it is an array of GenericMetric[]
. There is no way you can simplify that into an array of GenericMetric (GenericMetric[]
).
However, you can still manipulate the result of forkJoin(ox)
by making use of pipeable operators such as map,
forkJoin(ox)
.pipe(
map(res => {
const result = [];
res.map(elem => {
res.push(...elem)
});
return result;
}),
).subscribe(res => {
console.log(res);
// do the rest
})
Upvotes: 1
Reputation: 11864
My result is a unic element tab of tab, but if you have multiple tab of tab
[
[
[{a:1}, {a:2}, {a:3}],
[{a:4}, {a:5}]
],
[
[{a:6}, {a:7}, {a:8}],
[{a:9}, {a:10}]
]
]
, you can use switchMap
.
public getMetrics(url: string): Observable<GenericMetric[]> {
const ox: Observable<GenericMetric[]>[] = [];
res.forEach(elem => {
ox.push(this.http.get<GenericMetric[]>(url));
});
return forkJoin(ox).pipe(switchMap(allGenericMetrics => {
let genericMetrics: GenericMetric[] = [];
allGenericMetrics.forEach(metrics => {
genericMetrics = genericMetrics.concat(metrics);
});
return of(genericMetrics);
})
);
}
Upvotes: 0