byCoder
byCoder

Reputation: 9184

AngularJS (Restangular): wrap service method into timeout

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

Upvotes: 0

Views: 227

Answers (1)

Duncan
Duncan

Reputation: 95672

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.

Upvotes: 1

Related Questions