簡體   English   中英

http每500毫秒請求一次,直到請求完成Angular

[英]http request every 500ms until request complete Angular

我正在嘗試以每500ms不斷的請求請求服務器。 我想首先請求,如果請求在500ms之后沒有完成,我想再次發出相同的請求。 然后再次等待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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM