如何解决链接api调用并保存来自初始api结果的数据
如何在保留初始api响应数据的同时链接RXJS Angular httpclient可观察的api调用?
我有两个api调用,位置和人,位置是包含人the的位置数组。对于每个位置,我都会很to恼地打电话给人api响应。
问题在于,我需要保存最初的位置调用(例如他们所在的城市)中的数据,并且还需要保存人api调用中的人名。
根据我的阅读,您可以通过mergeMap链接api请求,但结果值将仅为最新的api数据。
位置Api通话数据
[
{
city: 'mycity',person-slug: 'person-x',},{
city: 'yourcity',person-slug: 'person-y',]
Api提供程序(RXJS Api呼叫)
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);
},[]),
不幸的是,诸如在合并映射中保存比api响应更多的数据之类的方法要么不起作用,要么将不订阅映射结果。
// 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))
};
反正有没有保存位置api调用数据 city 并添加到reduce函数中的最终响应数组中的方法?
一种解决方案是两个api调用,首先是保存位置数据数组,然后对每个联系人进行api调用并修改现有的位置数据数组。
解决方法
您可以使用forkJoin
运算符来并行调用它们,而不是分别触发每个app
。然后,您可以使用RxJS map
运算符以及Array map
和Object.assign
方法来返回第一个请求和第二个请求的组合结果。
尝试以下
this.http.get('fullPersonApiUrl' + value['person-slug'])
注意:
-
const req = this.http.get<Array<any>>('fullLocationApi').pipe( switchMap(values => { return forkJoin(values.map(value => this.http.get('fullPersonApiUrl' + value['person-slug']))).pipe( map(contacts => contacts.map((contact,index) => Object.assign(values[index],{contact: contact}))) ); }) );
仅在所有可观察到的源都完成后发射。 -
请求将是并行的,并且大多数浏览器对单个域的并发请求数都有硬性限制。如果遇到此问题,则可以考虑使用RxJS
bufferCount
运算符来制作buffered parallel requests。 -
forkJoin
的结果将是以下形式的数组
forkJoin(values.map(value => this.http.get('fullPersonApiUrl' + value['person-slug'])))
- 最终结果将是以下形式的对象数组
[
result from this.http.get('fullPersonApiUrl' + 'person-x'),result from this.http.get('fullPersonApiUrl' + 'person-y'),...
];
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。