如何解决Angular 9 服务嵌套的 http 请求
我需要对 2 个单独的端点进行查询,以提供我的组件所需的对象。
没有 | 端点 | 响应 |
---|---|---|
1 | /registry/colors |
{"colors":["red","green","blue","orange"]} |
2 | /color/{colorName} |
{"name":"red","details":["detail1","detail2","detail3"]} |
对于颜色数组中的每种颜色,我需要调用颜色细节端点并将所有这些颜色细节收集到一个颜色数组中。
getColors(): Observable<Color[]> {
return this.http.get<ColorRegistry>(this.registryUrl).pipe(
map((registry:ColorRegistry) => registry.colors.concatMap((colorName: string) => {
return this.http.get<Color>(this.colorUrl+"/"+colorName);
}))
)
}
我希望上述方法返回以下内容:
[
{"name":"red","detail3"]},{"name":"green",{"name":"blue",{"name":"orange","detail3"]}
]
显然,我的做法是错误的,我正在寻找使用可观察对象执行嵌套请求的正确方法。
解决方法
您的方向是正确的。
尝试以下更改。
- 用高阶映射运算符(如
map
)替换switchMap
运算符。 - 使用 JS
Array#map
并将colors
数组属性中的每个条目替换为第二次调用的响应。 - 使用
forkJoin
并行触发请求,最后合并结果。
getColors(): Observable<Color[]> {
return this.http.get<ColorRegistry>(this.registryUrl).pipe(
switchMap((registry: ColorRegistry) => {
return forkJoin(
registry.colors.map((colorName: string) =>
this.http.get<Color>(`${this.colorUrl}/${colorName}`)
)
) as Observable<Color[]>; // <— assert type here
})
);
}
,
registryUrl = '/registry/colors';
colorUrl(color) {
return `/color/${color}`;
}
return this.http.get<ColorRegistry>(this.registryUrl).pipe(
map(registry => from(registry.colors))
forkJoin(color => this.http.get<Color>(this.colorUrl(color)))
);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。