In my Angular app I retrieve a list of post from an API call and, for each fo the posts, I have to do another API call to retrieve the number of likes.
I can’t think of a clean way to do it, but current attempt of a solution is the following:
apiCall.pipe(
switchMap((posts: Post[]) => {
return posts.map((post: Post) => {
return this.getPostLikes(post.rootMessage).pipe(
map((likes: Like[]) => {
post.rootMessage.reactions = likes;
return post;
}),
);
});
}),
mergeAll(),
map((res: Post[]) => {
return { res, currentPage: page + 1 };
}),
)
I feel like the entire approach is wrong, but I can’t think at any other strategies.
>Solution :
It looks like you are trying to retrieve the likes for each post and then update the reactions field of the rootMessage object with the retrieved likes.
One way to do this in a cleaner way would be to use the forkJoin operator instead of the switchMap and mergeAll operators. The forkJoin operator allows you to perform multiple API calls in parallel and then wait for all of them to complete before continuing.
Here’s an example of how you can use the forkJoin operator to achieve what you want:
apiCall.pipe(
switchMap((posts: Post[]) => {
// create an array of observables for the API calls to get the likes for each post
const observables = posts.map((post: Post) => this.getPostLikes(post.rootMessage));
// use forkJoin to perform the API calls in parallel and wait for all of them to complete
return forkJoin(observables).pipe(
// once all the API calls are complete, update the reactions field of each post with the retrieved likes
map((likes: Like[][]) => {
return posts.map((post: Post, index: number) => {
post.rootMessage.reactions = likes[index];
return post;
});
}),
);
}),
map((res: Post[]) => {
return { res, currentPage: page + 1 };
}),
)
This should allow you to retrieve the likes for all the posts in parallel, and then update the reactions field of each post with the retrieved likes.
I hope this helps! Let me know if you have any questions.