angular - Angular - 将多个连续的 API 调用合并为一个结果
问题描述
我正在学习 rxjs,目前面临一些我不太确定如何解决的问题。我需要调用多个 API 请求,但问题是首先我需要获取名称列表,然后为每个名称获取其余数据。到目前为止,我已经提出了两个map
函数,第一个调用将获取名称列表,第二个map
将遍历列表并调用另一个请求以获取其余数据。我认为这是不好的做法,但我无法理解如何使用mergeMap
或forkjoin
实现更好的功能代码。
public getNames(): Observable<any> {
return this.httpClient.get<response>(someUrl)
.pipe(map(res => res.results), map((data)=>{
data.forEach(dat => {
this.getDataByName(dat.name).subscribe(res => {
dat.image = res.image;
});
});
return data;
}));
}
public getDataByName(name): Observable<any> {
return this.httpClient.get<any>(urlToGetMoreDataByName)
.pipe(map(res => res.results));
}
解决方案
如果我理解你的问题,我会尝试这些方面的东西
// remove the specification of the return type (: Observable<any>) since you
// should be able to achieve a more precise result using Typescript
// type inference
public getNames() {
return this.httpClient.get<response>(someUrl).pipe(
map(res => res.results),
// transform "data", which is an array of names in an array of Observables
// this first map is the rxjs map operator
map((data)=> {
// this inner map is the javascript method of the array
// for each dat it returns an Observable which emits when getDataByNme returns
return data.map(dat => this.getDataByName(dat.name).pipe(
// this is an rxjs map operator which retuns a
// dat object with the image property set
map(res => {
dat.image = res.image;
return dat
})
)
)
}),
// concatMap is used here to make sure that we fire the execution of the
// Observable created by forkJoin after the first get operation has returned
concatMap(arrayOfObservables => forkJoin(arrayOfObservables))
);
}
现在getNames
返回一个 Observable,一旦所有获取图像的调用都已执行,它就会发出。使用forkJoin
我们确保我们并行启动所有 http get 操作。如果我们想控制并发级别,我们可以使用其他运算符,例如`mergeMap。
您可能会在本文中找到一些关于哪些运算符可以与 http 操作一起使用的灵感。
推荐阅读
- django - 如何在 django 模型中调整图像文件的大小
- matlab - 每 100m 等值线图标签
- r - 为什么在 Power BI 中运行我的 R 代码时收到这些错误消息?
- javascript - 将内部包含数组的对象数组更改为一个对象
- spring-boot - 我收到 SSL 异常 - “java.security.cert.CertificateException:找不到与 IP 地址 XXXX 匹配的主题替代名称”
- java - 使用泛型类型使 Field.get 类型安全
- c# - 在 WPF 中单击上下文菜单时如何获取画布中的鼠标位置?
- django - 如何填充(链式)相关下拉列表
- c# - 应用程序是否有 GUI 或在后台运行
- java - 如何使用 mockito 框架为 VoltDb 表和 VoltDb 结果编写模拟?