marcel
marcel

Reputation: 3272

AngularJS provide success callback of a factory method

I have a simple factory that returns a promise after a async.-request.

getUpdates: function(){
    var q = $q.defer();
    $http.get(...)
    .success(function(data, status, headers, config) {
        q.resolve(data);
    })
    .error(function(data, status, headers, config) {
        q.reject(status);
    });
    return q.promise;
}

In my controller I just call the getUpdates-method and receive the promise.

var updates = factory.getUpdates();

How can I provide a success/error functionality of the getUpdates method?

factory.getUpdates().success(function(promise){...}).error(function(err)...

What do I have to add to my getUpdates function?

Upvotes: 1

Views: 1999

Answers (3)

sylwester
sylwester

Reputation: 16498

factory.getUpdates().then(
  //onSucess
  function(response)
  {
    // ...  
  },
  //onError

  function()
  {
    // ...      
  }
);

Upvotes: 0

runTarm
runTarm

Reputation: 11547

The $http service already return a promise, there is no need to use $q.defer() to create an another promise in this case. You could just write it like this:

getUpdates: function () {
  return $http.get(...);
}

This way the success() and error() methods will still be available.

Or if you really have a reason why you are using $q.defer(), please include it in the question.

Upvotes: 2

David Bohunek
David Bohunek

Reputation: 3201

You then function to handle the success and failure of the promise:

factory.getUpdates()
  .then(function(value) {
    // handle success
  }, function(reason) {
    // handle failure
  });

Upvotes: 1

Related Questions