What is the difference between success and then?
then
resolves an object that represents your http response. That is to say, the callback of the then
method take only one argument that has the following structure:
data – {string|Object}
– The response body transformed with the transform functions.
status – {number}
– HTTP status code of the response.
headers – {function([headerName])}
– Header getter function.
config – {Object}
– The configuration object that was used to generate the request.
statusText – {string}
– HTTP status text of the response.
On the other hand, success
is a shorthand function that will spread the different properties of the http response (except the statusText that is not very useful) into different arguments. Therefore the first argument of the success
callback will contain only the response body (the property response.data
) of the http response.
The following piece of code is taken from angular 1.4.5, and I was able to find it since angular 1.0.0:
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
When to use "then", and when to "success"?
For consistency with other promise libraries, I'll advise you to always use the standard then
method. If you replace $http.success
with $http.then
be careful that what you got in the response
object in the former, is equivalent to response.data
in the latter:
$http.get(...).success(function (response) {
return response;
}
is equivalent to:
$http.get(...).then(function (response) {
return response.data;
}