我正在寻求每500毫秒请求服务器持续请求。 我想先请求,如果请求在500ms后没有完成,我想再次提出相同的请求。然后再等待500ms并检查它是否不完整。我想重复这个过程,直到请求完成。
现在,我的请求看起来像这样:
$http({
method: method,
url:baseUrl,
headers: {
'Content-Type' : 'application/json; charset=utf-8',
'Data-Type': 'json'
},
data: resultService.sendData(true),
cache:false
})
.success(function(data,status,headers,config){ // accepts more parameters
$timeout(function(){
resultService.activeSearch=false;
$timeout(function(){
request= $filter('orderBy')(data,['price','id']);
},0);
},1000);
})
.error(function(){
resultService.activeSearch=false;
function(){
request={error:1};
};
});
};
我想过要用这样的东西
(function tick(){
$http({
method: method,
url:baseUrl,
headers: {
'Content-Type' : 'application/json; charset=utf-8',
'Data-Type': 'json'
},
data: resultService.sendData(true),
cache:false
})
.success(function(data,status,headers,config){ // accepts more parameters
request=data;
$timeout(tick,500);
$timeout(
function(){resultService.activeSearch=false;
},1000);
})
.error(function(){
$timeout(tick,500);
resultService.activeSearch=false;
function(){
request={error:1};
};
});
})();
这不按预期工作。我哪里错了?
答案 0 :(得分:1)
使用$ http
的超时参数
function MyCtrl($scope, $http){
$scope.logs=''
// Will try to get targetUrl every 500ms, then call successCallback with the data
function tryToGet(targetUrl,successCallback){
$scope.logs+='\n New attempt \n';
// Try a get with the timeout argument
var attempt = $http.get(targetUrl,{timeout:500})
// On error, try again
attempt.error(function(){
tryToGet(targetUrl,successCallback);
});
// On success, exectute the callback
attempt.success(successCallback);
}
function whenOk(data){
$scope.logs+=data
}
tryToGet('http://google.com', whenOk)
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<pre ng-controller="MyCtrl" ng-bind="logs">
</div>
&#13;