user1464139
user1464139

Reputation:

How can I make a $http call return a promise and data for $q?

I have the following script:

$q.all([
    getActive(),
    getUser()
])
.then(function (results) {
    var x = results[0];
    var y = results[1];
}


function getActive() {
    $http({
        url: '/api/Test/GetActive',
        method: "GET"
    })
};

function getUser() {
    $http({
        url: '/api/Test/GetUser',
        method: "GET"
    })
};

I was expecting to see that the variables x and y would contain the results of the $http calls but they both show as undefined.

Can someone suggest how I can make these calls return a promise. I actually thought $http did return a promise so I am confused.

Upvotes: 0

Views: 46

Answers (2)

John Munsch
John Munsch

Reputation: 19528

Here's a working example. I changed your code in a few small ways. Note: The returned promises from the individual calls, the simplified way of calling $http, and pulling the data out of the returned results in the then() function:

http://plnkr.co/edit/YStkRt?p=info

function MainCtrl($scope, $q, $http) {
  $q.all([
      getActive(),
      getUser()
  ])
  .then(function (results) {
      $scope.ip = results[0].data;
      $scope.headers = results[1].data;
  });

  function getActive() {
      return $http.get('http://ip.jsontest.com/');
  }

  function getUser() {
      return $http.get('http://headers.jsontest.com/');
  }
}

Upvotes: 1

pkozlowski.opensource
pkozlowski.opensource

Reputation: 117370

You seem to be missing the return statement in both the getActive() and getUser() functions.

Try this:

$q.all([
    getActive(),
    getUser()
])
.then(function (results) {
    var x = results[0];
    var y = results[1];
}


function getActive() {
    return $http({
        url: '/api/Test/GetActive',
        method: "GET"
    });
};

function getUser() {
    return $http({
        url: '/api/Test/GetUser',
        method: "GET"
    });
};

Upvotes: 2

Related Questions