我有一个从API获取数据的方法。
$http.get("https://httpstat.us/200?sleep=20000", header).then(
function successCallback(response) {
//logic
},
function errorCallback(response) {
}
);在某些测试用例中,API永远不会响应,所以我需要一种方法来处理这种情况。如果API花费的时间超过10秒,我需要返回一些数据。我尝试使用以下代码向请求添加超时
$http.get("https://httpstat.us/200?sleep=20000", {timeout: 10000}).then(但这只会中止请求,并转到错误回调。是否有其他方法可以在不使请求超时的情况下知道请求是否花费了永远的响应时间?
发布于 2020-06-25 23:37:40
Short anwser no ,没有内置的方式来通知http服务监听器请求很长。
但是,您可以构建一个延迟包装器,它将http调用封装在一个defer中,这样,如果服务的响应时间太长,您就能够通知侦听器,但您必须自己计时。
请看这篇文章,其中作者解决了与您类似的问题
https://www.peterbe.com/plog/angularjs-$q-notify-resolve-local-get-proxy
发布于 2020-06-26 00:55:08
如果你只需要在一段时间后运行一个函数,你可以使用$timeout。将你想要运行的函数以毫秒为单位传递给$timeout,它将返回一个计时器承诺。如果您的$http调用在超时之前解析,只需运行$timeout.cancel(\[promise\])并将您的计时器承诺传递给它。这将取消内部超时函数调用。
示例
var timer = $timeout(function() {
console.log("this request is taking too long...")
// tell the client it will take a while ...
}, 10 * 1000);
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
then(function(response) {
// handle successful response ...
$timeout.cancel(timer); // about your timeout function call
}, function(response) {
// handle rejection ...
});当然,您可以在finally子句中取消超时。(Plunker)
如果您不想为包装$http的每个函数编写相同的代码,可以考虑使用interceptor。
https://stackoverflow.com/questions/62578835
复制相似问题