angular - 如何检查两个http调用是否失败?
问题描述
我想进行 2 个 http post 调用,如果两个调用都失败,则显示错误,如果其中一个调用返回数据,那么我不想显示错误。
this.http.post<any[]>(URL, jsonBody1, postJson) //returns an Observable
this.http.post<any[]>(URL, jsonBody2, postJson) //returns an Observable
我可以通过将 http 帖子变成承诺来做到这一点吗?我尝试了下面的代码,但它不起作用。如果第一个 then() 抛出错误,它会跳过第二个 then() 并进入 catch(),但如果第一个 then() 抛出错误,我希望它执行下一个 then()。
this.http.post<any[]>(URL, jsonBody1, postJson).toPromise()
.then( data => {
// do something with data
})
.then( _ =>
this.http.post<any[]>(URL, jsonBody2, postJson).toPromise()
.subscribe( data => {
// do something with data
})
)
.catch( error => {
console.log(error);
});
解决方案
您可以只使用Observable
而不将其更改为Promise
:
forkJoin(
this.http.post<any[]>(URL, jsonBody1, postJson),
this.http.post<any[]>(URL, jsonBody2, postJson)).subscribe (
x => console.log(x),
error => console.log(error)
() => console.log('completed'))
上述方法可能比使用Promise
.
推荐阅读
- python - Python3 线程:为什么我只启动了一个线程时有 2 个线程处于活动状态?
- php - PHP数组转换成mysql表
- node.js - 将 typescript 文件导入 nodejs CLI 脚本
- python - 如何在满足无限循环内的elif条件时制作计时器,尽可能轻
- swift - SwiftUI 中的 GMSMarker 点击事件
- c - 传递 'myFunc' 的参数 5 使指针从整数而不进行强制转换 [-Wint-conversion]
- line - 我正在 python docx 中创建一个表,我需要在它下面加下划线。任何人有任何想法我该怎么做?
- python - 从 python 管理 Azure 中的事件中心
- ssis - 由于标识列,无法使用 SCD 组件
- cmake - CMake:分离测试目标(及其运行时依赖项)以存档并在其他地方执行