【问题标题】:http request every 500ms until request complete Angular每 500 毫秒 http 请求一次,直到请求完成 Angular
【发布时间】:2015-02-20 09:28:32
【问题描述】:

我正在寻求每 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};
          };
        });
})();

这不能按预期工作。我哪里错了?

【问题讨论】:

  • 这段代码的行为是什么?
  • 似乎500ms后根本没有发出新请求。是不是因为我在 500 毫秒后没有收到错误,因此没有发出新的请求?在我看来,在进入 .success 之前,我必须在其他地方启动 tick 功能?

标签: javascript angularjs http settimeout


【解决方案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>

【讨论】:

  • 这看起来不错。我现在将设置后端,看看它是否像我希望的那样运行。但是测试效果很好..
  • 谷歌页面没有超时,我没有找到一个不会回答的页面。如果页面关闭(404 错误),它将以最快的速度链接请求,因此可能应该添加重试之前的超时。是否必须恰好是 500 毫秒,或者超时错误可以是 1000 毫秒,其他错误可以是 500 毫秒吗?
猜你喜欢
  • 1970-01-01
  • 2018-05-24
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 2020-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多