首页 > 解决方案 > 如何检查两个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);
  });

标签: angularpromiserxjsangular-promise

解决方案


您可以只使用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.


推荐阅读