I am new to rxjs I am calling three api calls using the hacker new api. I want to concat response of the last api call to the second api call.
I want to achieve something like this.
[
{
"by": "john"
"title": "Sample title"
"time":1657786985
"karma": 123456 // this is from the third api call that i want to merge
},
{
"by": "jane"
"title": "Sample title 2"
"time":1657786333
"karma": 123456 // this is from the third api call that i want to merge
}
]
So far this is my code
this.service.fetchStories().pipe( // get list of id array
switchMap(idArray => forkJoin(
idArray.map(id => this.service.fetchStoryItems(id).pipe( // first api call
concatMap(itm => this.service.fetchUserById(itm.by)) // second api call i want to merge { karma } to the first api call
)))
),
take(1)
).subscribe(data => console.log(data));
But the result is I am getting only the response of the last api call. Can somebody help me. I am trying to learn rxjs.
CodePudding user response:
All you need to do is to pipe the third call again and merge the results.
this.service.fetchStories().pipe( // get list of id array
switchMap(idArray => forkJoin(
idArray.map(id => this.service.fetchStoryItems(id).pipe( // first api call
concatMap(itm => this.service.fetchUserById(itm.by).pipe(map(({karma}) => ({ ...itm, karma }))))
)))
),
take(1)
).subscribe(data => console.log(data));