如何设置使用angularjs ngResource($ resource)进行REST调用的时间限制

时间:2014-09-30 06:35:07

标签: java angularjs rest ngresource

我使用angularjs使用REST调用java api。



var app = angular.module("MyApp", ["ngResource","ngProgress"])
.factory('ConnectionData',function ($resource){
  return $resource('URI');
  });
  
  
function connectionTestController($scope,ConnectionData,ngProgress,$timeout){

$scope.connectionTest = function(){


    var success = function(data, getResponseHeaders){
      ngProgress.complete();
      $scope.datas = data;
      $('#testConnectionBtn').attr("disabled", false);
    };
    var failure = function(data){

      if(data.status == 404) {    

        $scope.errorString = data.status+", Request Error, Try Again"; 

      }else{

        $scope.datas = data.data;
        $scope.errMessage = $scope.datas.message;
      }
      ngProgress.complete();
      $('#testConnectionBtn').attr("disabled", false);

    };


    ConnectionData.get(success,failure);
  
  };
};
  

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>

<div class="col-md-4" ng-controller="connectionTestController">
     <h1>Connection Test</h1>
     <p><button class="btn btn-primary" ng-click="connectionTest()" id="testConnectionBtn">Click to Test</button></p>


     Code: <label id="code">{{datas.code}}</label><br>
     Status: <label id="status">{{datas.status}}</label><br>
     Data: <label id="data">{{datas.data}}</label><br>
     Message: <label id="message">{{errMessage}}</label><br><br>

     <label id="customeError">{{errorString}}</label><br>

   </div>
&#13;
&#13;
&#13;

单击按钮时正在进行REST调用。我想对请求设置时间限制。 (例如:30秒。)如果在时间限制内未收到回复,则应显示错误消息。

1 个答案:

答案 0 :(得分:3)

您可以在操作上设置超时选项,例如:

{ 
   'get':    {method:'GET', timeout:2000},
   'save':   {method:'POST', timeout:2000},
   'query':  {method:'GET', isArray:true, timeout:2000},
   'remove': {method:'DELETE', timeout:2000},
   'delete': {method:'DELETE', timeout:2000}
};

这可以在ConnectionData工厂中完成。

之后,你可以这样:

  ConnectionData.get({id:'SomeId'}).$promise.then(success).catch(failure);

这有意义吗?