angular - RxJs 相当于 Promise 链
问题描述
当使用 Promise 链接 API 调用时,我会这样做:
this.http.get('/api/hello').toPromise().then(res => {
return this.http.get('/api/there/' + res.id).toPromise()
}).then(res => {
console.log('res from 2nd call', res)
}).catch(err => {
console.log('err', err)
})
当第二个响应需要来自第一个响应的数据才能进行时,您如何使用 Observables 链接这样的 API 调用?
TIA
解决方案
您应该使用flatMap
请访问此网址https://stackblitz.com/edit/angular-6-rxjx-stuff。我创建了这个项目来测试 RxJS。
你可以看到下面的函数。
test__flatMap() {
const post$ = this.getPosts();
const users$ = this.getUsers();
const users2$ = this.getUsers();
post$.pipe(
flatMap(data => {
console.log('data 1 >>> ', data);
return users$;
}),
flatMap(data => {
console.log('data 2 >>> ', data);
return post$;
}),
).subscribe(data => { console.log(`In the end >>> `, data); });
}
推荐阅读
- c# - Identity Server 4 隐式流 - 未知错误
- python - 本地主机的 boto3 事件 / eventBridge 配置
- javascript - 如何将多元素 JSON 对象的不同级别的值打印到 Google 表格中?
- java - 正则表达式一个衬里来提取模式匹配组
- python - 对大量数运行压力测试时出错(在 long_scalars 中遇到溢出)
- reactjs - 如何在react redux中仅选择一个映射数据上的复选框
- amazon-web-services - 停止 AWS RDS 实例以避免付款
- android - 如何在 Flutter 中制作独特按钮的 Listview?
- git - 如何在dotnet core中组织多个git包
- reactjs - 使用 Absolute Imports 更新所有导入