Skip to content Skip to sidebar Skip to footer

Angular - Multiple $http.get Requests For Data

What is the best approach to take when making multiple calls to an API for data needed in the same view? For example, you have multiple select boxes which need to contain data pull

Solution 1:

You can use q.all(), as it accepts an array of promises that will only be resolved when all of the promises have been resolved.

$q.all([
      $service.getDataOne(),
      $service.getDataTwo()
    ]).then(function(data){
      $scope.dataOne = data[0];
      $scope.dataTwo = data[1];
 });

If you look at the link, q.All() is at the very bottom of the page

Solution 2:

I believe you are looking for the $q service.

http://jsfiddle.net/Zenuka/pHEf9/21/

https://docs.angularjs.org/api/ng/service/$q

functionTodoCtrl($scope, $q, $timeout) {
functioncreatePromise(name, timeout, willSucceed) {
    $scope[name] = 'Running';
    var deferred = $q.defer();
    $timeout(function() {
        if (willSucceed) {
            $scope[name] = 'Completed';
            deferred.resolve(name);
        } else {
            $scope[name] = 'Failed';
            deferred.reject(name);
        }
    }, timeout * 1000);
    return deferred.promise;
}

// Create 5 promisesvar promises = [];
var names = [];
for (var i = 1; i <= 5; i++) {
    var willSucceed = true;
    if (i == 2) willSucceed = false;
    promises.push(createPromise('Promise' + i, i, willSucceed));
}

// Wait for all promises    $scope.Status1 = 'Waiting';
$scope.Status2 = 'Waiting';
$q.all(promises).then(
    function() { 
        $scope.Status1 = 'Done'; 
    }, 
    function() { 
        $scope.Status1 = 'Failed'; 
    }
).finally(function() {
    $scope.Status2 = 'Done waiting';
});
}

Credit: Code shamelessly stolen from unknown creator of fiddle.

Solution 3:

If it for loading the looku pdata for all the dropdowns, I would make one call to get all the lookup data in one single payload. Something like this. Each property value is an array of items for each dropdown.

{"eventMethods":[{"name":"In Person","id":1},{"name":"Phone","id":2}],"statuses":[{"name":"Cancelled","id":42},{"name":"Complete","id":41}]}

Post a Comment for "Angular - Multiple $http.get Requests For Data"