Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, e.g. a returns before b, b returns before a?

like image 922
brushleaf Avatar asked Mar 31 '13 04:03

brushleaf


People also ask

What is use of HTTP get in Angular?

Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. The return type varies based on the observe and responseType values that you pass to the call.

What is the return type of HTTP get in Angular?

get() returns Observable of JSON response type. If we want to filter data by passing parameters, we can pass options object parameter containing params attribute as following. Now find the extractData() method. The RxJS map() is used to map response object into other object if needed.

Does Angular HttpClient use Fetch?

Angular offers HttpClient to work on API and handle data easily. In this approach HttpClient along with subscribe() method will be used for fetching data.


1 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 */
  });
}
like image 95
Kevin Hakanson Avatar answered Oct 05 '22 23:10

Kevin Hakanson