Home » Angularjs » How to bundle Angular $http.get() calls?

How to bundle Angular $http.get() calls?

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have a controller that needs to retrieve two separate REST resources that will populate two dropdowns. I would like to avoid populating either of them until both $http.get() calls have returned, so that the dropdowns appear to be populated at the same time, instead of trickling in one after the other.

Is it possible to bundle $http.get() calls and elegantly set the $scope variables for both returned arrays, without having to write state logic for both scenarios, e.g. a returns before b, b returns before a?

Answers:

The return value of calling the Angular $http function is a Promise object using $q (a promise/deferred implementation inspired by Kris Kowal’s Q).

Take a look at the $q.all(promises) method documentation:

Combines multiple promises into a single promise that is resolved when
all of the input promises are resolved.

Parameters

  • promises – {Array.<Promise>} – An array of promises.

Returns

{Promise} – Returns a single promise that will be resolved with an array of values, each value corresponding to the promise at the same index in the promises array. If any of the promises is resolved with a rejection, this resulting promise will be resolved with the same rejection.

You can use $q.all to “join” the results of your http calls, with code similar to:

app.controller("AppCtrl", function ($scope, $http, $q) {

  $q.all([
    $http.get('/someUrl1'),
    $http.get('/someUrl2')
  ]).then(function(results) {
     /* your logic here */
  });
}

Questions:
Answers:

do you mean something like this:

function someController( $scope, $http, $q ) {
    var first_meth = $http.get("first_url"),
        second_meth = $http.get("second_url");
    $q.all([first_meth, second_meth]).then(function(all_your_results_array) { 
        //here you'll get results for both the calls
    });
}

Ref: Angular JS Doc

Questions:
Answers:

You could use the Async javsscript library here: https://github.com/caolan/async.

Use the series call. It will make the 2 calls and then call one callback when both are done.