tyler.frankenstein
tyler.frankenstein

Reputation: 2344

Chaining two $http calls and returning the result of the second

I have an Angular Service that I'd like to use to perform two $http calls, and return the result of the second. Here's the service:

angular.module('myApp', [])
  .service('farm', ['$http']);

function farm($http) {
  this.saveFruit = function(fruit) {
    return $http.get('http://example.com/get-token').success(function(token) {
        return $http({
            method: 'POST',
            url: 'http://example.com/save-fruit',
            headers: { 'X-CSRF-Token': token },
            data: { fruit: fruit }
        });
    });
  }
}

At this point, the code works fine. I'm able to "save some fruit", which grabs a token for itself via GET, then sends the data via POST, and everything is saved up in the cloud, great.

To call this service, I'm using code like this:

var fruit = { name: 'Apple', color: 'red' };
farm.saveFruit(fruit).success(function(result) {
    console.log(result);
});

However, the console.log() always prints out the result of the $http GET, instead of the POST.

How do I get the result of the $http POST call when calling saveFruit?

Upvotes: 0

Views: 52

Answers (2)

JB Nizet
JB Nizet

Reputation: 691685

success() doesn't allow chaining promises. Use the real thing: then().

return $http.get('http://example.com/get-token').then(function(response) {
  return $http({
    method: 'POST',
    url: 'http://example.com/save-fruit',
    headers: { 'X-CSRF-Token': response.data },
    data: { fruit: fruit }
  });
}).then(function(response) {
  return response.data;
});

and

var fruit = { name: 'Apple', color: 'red' };
farm.saveFruit(fruit).then(function(result) {
    console.log(result);
});

Upvotes: 2

Explosion Pills
Explosion Pills

Reputation: 191729

Using the .success and .error methods of $http breaks the promise chain. This is undocumented and could be considered a bug.

In order to continue the promise chain, use .then (and .catch, as needed).

return $http.get('http://example.com/get-token').then(function(response) {
    return $http({
        method: 'POST',
        url: 'http://example.com/save-fruit',
        headers: { 'X-CSRF-Token': response.data },
        data: { fruit: fruit }
    });
});

Upvotes: 3

Related Questions