angular - 如何在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 响应,则循环应该转到下一个顺序并检查请求是否返回正确响应或再次错误。有谁可以帮我离开这里吗?
解决方案
当服务器响应 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
}
});
推荐阅读
- python - 如何使用python解析.in文件并将内容写入.out文件
- scala - 将 scala 映射值与列表进行比较,并为列表中不存在的键返回默认值
- sql - 需要单独计算每个客户在选定日期的票数,以及每天的销售数量和总数
- python - centos 7机器中的python 3.6.7 UnicodeEncodingError
- amazon-web-services - 在 AWS Step Functions 中跨循环传递数据
- kubernetes - 在工作节点和控制平面之间引入代理后,Kubernetes 工作节点处于 NotReady 状态
- webhooks - 如何将函数应用与 SharePoint webhook 一起使用?
- angular - ng2-completer 选择事件未在鼠标单击时触发
- drools - 如何遍历drools决策表中的对象列表?
- ios - 使用 PaypalSDK iOS 导航颜色在 iOS 中未更改