How to chain RXJS Angular httpclient observable api calls whilst retaining initial api response data?
I have two api calls, location and person, the location is an array of locations that contains the person slug. For each location, I would get the slug to call the person api response.
The issue is that I need to save data from the initial location call, like their city, and also save the person's name from person api call.
From what I've read, you can chain api requests by mergeMap, but the resulting value would be the latest api data only.
Location Api Call Data
[
{
city: 'mycity',
person-slug: 'person-x',
},
{
city: 'yourcity',
person-slug: 'person-y',
},
]
Api Provider (RXJS Api Call)
private http: HttpClient; // Angular Http Client
const req = this.http.get<Array<any>>('fullLocationApi')
.pipe(
// Split up initial array of objects response into stream of objects
mergeMap(val => {
return val;
}),
mergeMap(val => {
// Call the second Api to get the person details
const personSlug = val.person-slug;
const personUrl = 'fullPersonApiUrl' + personSlug;
return this.http.get(personUrl);
}),
// Combine together the single stream into an array
// Only saves the city api call data, doesn't save the location city
reduce((dataArr, data) => {
return dataArr.concat(data);
}, []),
Unfortunately, something like saving more data than just the api response in merge map either doesn't work or won't subscribe to the map result.
// Doesn't work, but would be ideal, that way there's data saved from the old call as well
mergeMap(val => {
const personSlug = val.person-slug;
const personUrl = 'fullPersonApiUrl' + personSlug;
return {
old: val,
contact: this.http.get(personUrl))
};
Is there anyway to save the location api call data city to add to the final response array in the reduce function?
One solution would be two api calls, first to save an array of the location data, then have an api call for each contact and modify the existing array of location data.