Right now for the operation mentioned in title I have the following code
from(["url_1", "url_2"])
.pipe(
concatMap(url=> this.vocabularyService.getSimilarProducts(url)
.pipe(concatMap(x => x.items))
),
toArray()
)
.subscribe(res => console.log(res));
What it does that for each URL in the array of URLs it makes an API call that returns something like this
class Response {
items: Object[] // this is a specific type, but let's omit this for simplification
}
After receiving the response I again need to do a concatMap() to retrieve each of the items array item and eventualy I do the toArray() to somewhat flatten each item into single array and log it into console.
Does RxJs have any specific operator to do this kind of thing or is it possible to avoid my stacking of concatMap() operators?
>Solution :
You can use reduce to flatten the array like so.
import { Component } from "@angular/core";
import { from, of } from "rxjs";
import { concatMap, reduce } from "rxjs/operators";
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular';
subscripber = {
next: (i) => console.log(i),
complete: () => console.log('end'),
};
ngOnInit() {
from(['url_1', 'url_2'])
.pipe(
concatMap((url) =>
of({
items: [1, 2, 3],
})
),
reduce((acc, one) => {
acc.push(...one.items);
return acc;
}, [])
// smaller version
// reduce((acc, one) => [...acc, ...one.items], [])
)
.subscribe((res) => console.log(res));
// Open the console in the bottom right to see results.
}
}