我有一种方法可以从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(
但这只会中止请求并转到错误回调。是否有另一种方法可以知道请求是否在没有真正使请求超时的情况下进行永久响应?
答案 0 :(得分:1)
短提示否,没有可用于通知http服务侦听器请求很长的方法。
但是,您可以构建一个将http调用封装为一个延迟的延迟包装器,以便在服务响应时间过长时可以通知您的侦听器,但您必须自己为其计时。
看看这篇文章,作者解决了与您类似的问题
https://www.peterbe.com/plog/angularjs-$q-notify-resolve-local-get-proxy
答案 1 :(得分:0)
如果您只需要在一段时间后运行函数,则可以使用$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。