My first api returns following data
{
"resp": [
{
"id": "932e",
"name": "jon"
},
{
"id": ...
"name": ..,
}
]
}
I have to loop through this array and make another call to API using above id, which returns data like this
{
"posts": [
{
"id": "1111",
"title": "post on facebook"
},
{
"id": "2222",
"title": "post on covid"
}
]
Final data should be in this format
{
"resp": [
{
"id": "932e",
"name": "jon",
"posts": [
{
"id": "1111",
"name": "post on facebook"
},
{
"id": "2222",
"name": "post on covid"
}
]
}
]
}
signature of method which makes call to 2nd api like this
public getUsersPost(userId) {
return this.datasetService.getPosts(userId).pipe(
map(ds => {
return ds.posts
}));
}
Not sure how to use map, mergreMap or concatMap for >
Thanks in advance
Your choice of mapping operator depends on the loading strategy you want. mergeMap
sends all the requests in parallel (you can limit the maximum number of simultaneous requests), whereas concatMap
will execute them in series. I'd also recommend splitting the first Array into its component parts.
I suspect you want something along these lines:
const populatedUsers$ = this.getUsers.pipe(
mergeMap(userArray => from(userArray)), // now emitting each user separately)
mergeMap(user => this.getUsersPost(user.id).pipe(
map(ds => ({ ...user, posts: ds.posts }))
), null, 5), // maximum of 5 concurrent requests
toArray() // convert everything back to a single array
);