【发布时间】:2019-04-15 04:03:45
【问题描述】:
我正在努力弄清楚如何使用 Angular http 和 Promise 检测请求超时。我正在使用以下代码来格式化来自我的 API 的响应,并且它当前正在超时,我想处理错误消息,当我的 API 返回实际错误消息时,这里的代码确实有效,只是它甚至没有被命中当 API 超时时。
我找不到任何关于 Angular http 有办法处理超时的文档,所以任何东西都会有帮助,谢谢!
代码:
/**
* GET from the API
* @param params What to send
* @param path Where to go
*/
public get(path, params): Promise<any> {
return this.formatResponse(
this.http.get(this.apiUrl + path, params)
);
}
/**
* Takes the API response and converts it to something usable
* @param response Promise of formatted data
*/
public formatResponse(response): Promise<any> {
return response
.toPromise()
.then(r => r.json().data)
.catch(e => {
console.log('hitting error');
const errors = e.json().errors;
let error = 'Something went wrong, please try again in a few minutes.';
if (errors && errors.length > 0) {
error = errors[0].message;
}
// Create alert
this.utilities.createAlert(
'Whoops!',
error
);
// Throw the error
throw new Error(error);
});
}
在网络选项卡中监控时,我看到:
加载资源失败:请求超时。
【问题讨论】:
-
网络标签中显示什么错误代码?
.catch()将捕获 HTTP 错误。 -
@Matt
Failed to load resource: The request timed out. -
您在网络选项卡中看到了什么? HTTP 超时应该是代码 408。
-
它没有错误代码。
-
如果你使用 rxjs,你可以使用类似这样的东西:stackoverflow.com/questions/51405688/…,我不知道是否可以通过 Promise 完成类似的事情。同样使用 rxjs,您可以更快地发现错误并用它做自己的事情或生成一些特殊的东西
标签: javascript angular typescript ionic-framework