简体   繁体   中英

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

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, eg a returns before b, b returns before a?

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 */
  });
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM