AngularJS (Restangular): wrap service method into timeout

Issue

In basic $http i had such code (this is a service):

var getSomeData = function() {
    var deferred = $q.defer();
    $timeout(function() {
      $http.get('...mylongurl', {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .success(function(response) {
        deferred.resolve(response);
      })
      .error(function(error) {
        deferred.reject(error);
      });
    }, 2000);
    return deferred.promise;
}

and i transformed it into restangular so:

var getSomeData = function() {
  var user = Restangular.one('mylongurl');
  $timeout(function(){
    return user.get().then(function (response) {
      return response;
    }, function(error){
      return error;
    });
  }, 2000);
  return user;
};

and then in controller i use it so:

someService.getSomeData().then()...

but now with timeout i get: someService.getSomeData().then is not a function

Solution

You can take advantage of the fact that $timeout returns a promise:

function getSomeData() {
  var user = Restangular.one('mylongurl');
  return $timeout(2000)
      .then(function(){
           return user.get();
       });
}

Older versions of angular may still require an empty function passed to the timeout $timeout(function(){}, 2000), but if you are using a recent one you can just omit it altogether.

Answered By – Duncan

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.