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?
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.
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.
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.
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 thepromises
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 */
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With