Search code examples
javaangularjsrestngresource

how to set a time limit for a REST call made with angularjs ngResource ($resource)


I'm using angularjs to call a java api using REST.

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>

REST call is being made when the button is clicked. I want to put a time limit to the request. (example: 30 seconds.) If the reply isn't received within the time limit then it should display an error message.


Solution

  • You can set an timeout option on your actions, something like:

    { 
       '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}
    };
    

    this can be done in the ConnectionData factory.

    After that, you can all it like this:

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

    Does that make sense?