http请求,每500ms一次,直到请求完成Angular

http request every 500ms until request complete Angular

本文关键字:请求 Angular 一次 500ms http      更新时间:2024-02-15

我正在寻求每500ms不断请求服务器。我想先请求,如果500毫秒后请求不完整,我想再次提出同样的请求。然后再等待500毫秒,检查是否不完整。我想重复这个过程,直到请求完成。

现在,我的请求如下:

$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};
          };
        });
})();

这并没有按预期工作。我哪里错了?

使用$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>