Abdul Salam Shaikh Abdul Salam Shaikh - 17 days ago 4
Javascript Question

Using $timeout for repetitive rest calls in angular js

I am trying to implement a service which makes a rest call every 5 seconds. Previously I was using $interval but I realized using could get in troubles if a request takes longer than 5 sec because of internet connection problems.

service.fetchData= function () {
//UpdateHandler is my handler function which just fills my json array
restApiService.requestFromApi("REST" + '?latitude=' + latestCoords.latitude + '&longitude=' + latestCoords.longitude + '&radius=' + config.radiusInMetres, updateHandler);
};

$timeout(service.fetchData, 5000);


fetchData is still called just once.

How can we use timeout for multiple calls and using promises(I am not very familiar with promises)

Answer

If you want to stick to $timeout, you should call the function recursively, with a timeout, then request to API is finished.

service.fetchData= function fetchData() {
    //UpdateHandler is my handler function which just fills my json array
    restApiService.requestFromApi("REST" + '?latitude=' + latestCoords.latitude + '&longitude=' + latestCoords.longitude + '&radius=' + config.radiusInMetres, updateHandler)
    .finally(function(){ 
          $timeout(fetchData, 5000)// Call new fetchData after finish previous
         });
};

$timeout(service.fetchData, 5000);

Example

angular.module('ExampleApp', [])
  .controller('ExampleController', function(restApiService, $timeout) {
    var vm = this;
    this.fetchData = function() {
      console.log("start request");
      restApiService.requestFromApi("data")
        .then(function() {
          console.log("success response");
        })
        .finally(function() {
          console.log("request again");
          fetchByTimeout();// Call new fetchData after finish previous
        });
    };

    function fetchByTimeout() {
      $timeout(vm.fetchData, 5000);
    }
    fetchByTimeout();
  })
  // Service for simulate long API call
  .service("restApiService", function($q, $timeout) {
    return {
      requestFromApi: function(request) {
        var defer = $q.defer();
        //simulate 10 seconds API call
        $timeout(defer.resolve, 10000);
        return defer.promise;
      }
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="ExampleController as vm">

  </div>
</div>

Comments