angular - 如何在Angular 7中使用管道强制http请求中的顺序
问题描述
我有一个组件可以调用一些对不同 url 的 http 请求。每个请求都被实现为一个可观察的。
getIds():Observable<any[]> {
return this.http
.post(url1, '')
.pipe(map(({ Ids}: any) => Ids.map(item => ({Id: item.Id }))));
}
getNames(data: Names):Observable<any[]> {
return this.http
.post(url2,element)
.pipe(map(({ Results }: any) => Results[0].map(item => ({id: item.ID, name: item.CVSS}))));
}
从组件,我需要做,
ngOnInit() {
this.Ids = this.getIds();
Ids.forEach(function(element)
this.getNames();
}
有人可以展示我如何执行此命令吗?
解决方案
从 RXJS 导入 switchMap
import { switchMap } from 'rxjs/operators'
然后通过管道传输到返回的 observable 上的地图
this.getIds().pipe(
switchMap((id: string) => this.getNames(id))
).subscribe((response) -> {
console.log(response)
})
推荐阅读
- webpack - Webpack 相同的加载器,不同的规则
- drop-down-menu - 单击 li 时会出现一个下拉菜单,但再次单击 li 下拉菜单未关闭
- linux - 将 gstreamer 的输出重定向到 OpenCV
- python - Python。从文本文件中获取数据并放入数据框中
- java - 使用新的 Java 模块系统加载服务提供者还缺少什么?
- neural-network - 什么是广义前馈神经网络 (GFF)?
- java - Scala 不会在 IntelliJ 中运行
- sql - 存储过程中的分组和循环
- firebase - Firestore fetch 永远不会在 Flutter 代码中执行
- java - 在 XML 标记中解析和连接值