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) {
      .error(function(error) {
    }, 2000);
    return deferred.promise;

and i transformed it into restangular so:

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

and then in controller i use it so:


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


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

function getSomeData() {
  var user ='mylongurl');
  return $timeout(2000)
           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.