0

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)

3 Answers 3

1

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>

Sign up to request clarification or add additional context in comments.

3 Comments

While using finally, I often get this error Uncaught TypeError: Cannot read property 'finally' of undefined(…)
@AbdulSalamShaikh Function requestFromApi need return a promise. Show code for requestFromApi function.
0

You can't use $timeOut for multiple calls.As per the docs, the return value of calling $timeout is a promise, which will be resolved when the delay has passed and the timeout function, if provided, is executed. In short, it will be executed once, after the time delay has lapsed

What you were previously using $interval is correct for your requirement. To avoid the problem that you are suggesting ( slow internet, and a new call before the previous is completed), use a flag.

//if(flag is false)
// set flag to true and make http call 
// upon return from call, set flag to false

Now use this login within your $interval function call. Hope this helps.

2 Comments

How can i use incorporate promise to this code, if you can throw some light on that ?
The promise would be returned from a service where the http call should be made. The flag should be in your controller which calls the service. And the $interval also within controller which would call the service based on the flag condition
0

For multiple calls you must use $interval.

var myapp = angular.module("myapp", []);

myapp.controller("MyController", function($scope, $interval){

    $interval(isLoggedIn, 5000);

});

function isLoggedIn() {
    console.log("Interval occurred");
    // call your service method`enter code here` here
}

For Promise in angularJs check the link...

http://haroldrv.com/2015/02/understanding-angularjs-q-service-and-promises/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.