Angular 链接api调用并保存来自初始api结果的数据
如何在保留初始api响应数据的同时链接RXJS和httpclient可观察的api调用? 我有两个api调用,location和person,location是一个包含person段塞的位置数组。对于每个位置,我都会让slug调用person api响应 问题是我需要保存来自初始位置调用的数据,比如他们的城市,还需要保存来自person api调用的人名 据我所知,您可以通过mergeMap链接api请求,但结果值只能是最新的api数据 位置Api调用数据Angular 链接api调用并保存来自初始api结果的数据,angular,api,http,rxjs,Angular,Api,Http,Rxjs,如何在保留初始api响应数据的同时链接RXJS和httpclient可观察的api调用? 我有两个api调用,location和person,location是一个包含person段塞的位置数组。对于每个位置,我都会让slug调用person api响应 问题是我需要保存来自初始位置调用的数据,比如他们的城市,还需要保存来自person api调用的人名 据我所知,您可以通过mergeMap链接api请求,但结果值只能是最新的api数据 位置Api调用数据 [ { city: 'my
[
{
city: 'mycity',
person-slug: 'person-x',
},
{
city: 'yourcity',
person-slug: 'person-y',
},
]
Api提供程序(RXJS Api调用)
是否仍要保存位置api调用数据city,以添加到reduce函数中的最终响应数组中
一种解决方案是两个api调用,首先保存一个位置数据数组,然后为每个联系人调用一个api调用并修改现有的位置数据数组。而不是触发每个
this.http.get('fullPersonApiUrl'+value['person-slug'])
您可以使用操作符分别并行调用它们。然后,您可以使用RxJS运算符以及数组和方法返回第一个和第二个请求的组合结果
试试下面的方法
const req=this.http.get要生成的运算符
来自forkJoin(values.map(value=>this.http.get('fullPersonApiUrl'+value['person-slug']))的结果将是表单的数组
- 最终结果将是表单的对象数组
您可以通过管道传输this.http.get(personUrl))
像this.http.get(personUrl)).pipe(map(res=>hereCombine(res+locDetails)))
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);
}, []),
// 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))
};
[
result from this.http.get('fullPersonApiUrl' + 'person-x'),
result from this.http.get('fullPersonApiUrl' + 'person-y'),
...
];
[
{
contact: result from this.http.get('fullPersonApiUrl' + 'person-x')
city: 'mycity',
person-slug: 'person-x',
},
{
contact: result from this.http.get('fullPersonApiUrl' + 'person-y')
city: 'yourcity',
person-slug: 'person-y',
},
...
]