首页 > 解决方案 > 如何在Angular中的404响应后继续循环?

问题描述

我查了一下你是否可以忽略 404 响应并继续你的循环,但我没有找到关于 Angular 的解决方案,所以我想在这里问这个问题。

我有以下代码:

  for(let order of orders){
      this.api.getURL(order.resource_url).then(data =>
          this.detail = data;
      );
      // Do something with this.detail ...
  }

如果请求返回 404 响应,则循环应该转到下一个顺序并检查请求是否返回正确响应或再次错误。有谁可以帮我离开这里吗?

标签: angulartypescripthttp-status-code-404httpresponse

解决方案


当服务器响应 404 时,您会收到异常。为避免它,您必须捕获该错误:

for(let order of orders){
  this.api.getURL(order.resource_url).then(data => {
    this.detail = data;
  }, error => {
    // error has been caught
  });
}

更新

您正在苦苦挣扎,因为您正在尝试以同步方式使用异步 api :) 尝试过滤失败的响应,然后进行计算:

Promise.all(
 orders.map(order => this.api.getURL(order.resource_url).catch(() => null))
).then(responses => {
  const successfulResponses = responses.filter(response => response != null)
  for(let data of successfulResponses) {
    // your following code
  }
});

推荐阅读