Asik
Asik

Reputation: 7977

Angular $http service- success(), error(), then() methods

When should I use then() method and what is the difference between then(), success(), error() methods ?

Upvotes: 3

Views: 2467

Answers (2)

Saidh
Saidh

Reputation: 1141

then() method fires in both the success and failure cases. The then() method takes two arguments a success and an error callback which will be called with a response object.

Upvotes: 1

Chandermani
Chandermani

Reputation: 42669

Other than the success un-wraps the response into four properties in callback, where as then does not. There is subtle difference between the two.

The then function returns a promise that is resolved by the return values for it's success and error callbacks.

The success and error too return a promise but it is always resolved with the return data of $http call itself. This is how the implementation for success in angular source looks like:

  promise.success = function(fn) {
    promise.then(function(response) {
      fn(response.data, response.status, response.headers, config);
    });
    return promise;
  };

To understand how it can affect our implementation, consider an example where we retrieve whether user exists based on email id. The http implementation below tries to retrieve the user based on userid.

$scope.userExists= $http.get('/users?email='[email protected]'')
                        .then(function(response) {
                            if(response.data) return true;  //data is the data returned from server
                            else return false;
                         });

The promise assigned to userExists resolves to either true or false;

Whereas if we use success

$scope.userExists= $http.get('/users?email='[email protected]'')
                        .success(function(data) {    //data is the response user data from server.
                            if(data) return true;  // These statements have no affect.
                            else return false;
                         });

The promise assigned to userExists resolves either a user object or null, because success returns the original $http.get promise.

Bottom line is use then if you want to do some type of promise chaining.

Upvotes: 2

Related Questions