AngularJS Function After Multiple Async Service Calls

Adam Rodger

I have a REST API that I want to call from an AngularJS service like this:

angular.module('myModule').service('MyApi', ['$http', function($http) {
    return ({
        resources: resources,
        details: details
    });

    function resources() {
        return $http.jsonp('/api/resources');
    }

    function details(key) {
        return $http.jsonp('/api/details/' + id);
    }
}]);

There are other implementation details removed there such as authentication that aren't important. The API is provided by a third party so I can't change it.

GET /api/resources returns something like:

[{ "key": "one" }, { "key": "two" }]

GET /api/details/one returns something like:

{ "count": 5 }

I then have a controller where I want to call MyApi.resources(), wait for the results and then for each result, call MyApi.details(resource). When the final call to MyApi.details(resource) completes, I want to run a function to aggregate some results from the set of details, but I can't work out how to trigger this at the end.

My controller currently looks like this:

angular.module('myModule').controller('MyCtrl', ['$scope', 'MyApi', function($scope, MyApi) {
    $scope.results = new Array();

    MyApi.resources().then(function(response) {
        var resources = response.data;
        var length = resources.length;

        for (var i = 0; i < length; i++) {
            MyApi.details(resources[i].key).then(function(response) {
                $scope.results.push(response.data.count);
            });
        }
    });

    // how do I get this line to run only after all the results are returned?
    $scope.total = $scope.results.reduce(function(a, b) { return a + b; }, 0);
}]);

What is the best way to achieve the aggregation at the end?

Joe Samanek

You can use deferred's function $q.all.

angular.module('myModule').controller('MyCtrl', ['$scope', 'MyApi', '$q', function($scope, MyApi, $q) {
    $scope.results = new Array();

    MyApi.resources().then(function(response) {
        var resources = response.data;
        var length = resources.length;

        var defer = $q.defer();
        var promises = [];

        angular.forEach(resources, function(value) {
            promises.push(MyApi.details(resources[i].key));
        });

        $q.all(promises).then(function() {
            $scope.total = $scope.results.reduce(function(a, b) { return a + b; }, 0);        
        });
    }
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

AngularJs : Multiple Calls for $http service

How do I make multiple async calls, then execute a function after all calls have completed?

AngularJS and an async function inside of a service

Multiple function calls, but single execution of async Task

Multiple calls to async function with cache in C#

Checking results from multiple async web-service calls

Redis connection is lost after multiple calls to function

Undefined behaviour after multiple calls to a print function

Execute a function after N async calls in javascript/jQuery

How to call a function after all async calls in loop are done?

Abort AngularJS $http request, deeply nested in multiple service calls

Multiple async calls blocking

Multiple resolve() calls inside promise returning async function

nodejs- Best method to perform multiple async calls inside a function?

calculate execution times of async function over multiple calls

How make multiple calls to async function collapse into 1 task?

AngularJS REST service calls

Async function that calls itself

Queuing Async Function Calls

Issues with DbContext getting disposed after multiple calls to service

AngularJS + $q, Do something after multiple ajax calls have finished

Multiple $http calls in AngularJS

For Loop with Multiple Async calls - Repeatedly Prints Last Item in Second Async Function

Angularjs function calls order

AngularJS function in service throwing 'not a function error' after route change?

Multiple Async Calls with Pause Between Calls

Result of changing nonlocal variable in a inner function after multiple calls

Subscribe to multiple async http calls

Multiple Async Calls in C++