Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I need to do two $http.get call and I need to send returned response data to my service for doing further calculation.

I want to do something like below:

function productCalculationCtrl($scope, $http, MyService){
    $scope.calculate = function(query){

            $http.get('FIRSTRESTURL', {cache: false}).success(function(data){
                $scope.product_list_1 = data;
            });

            $http.get('SECONDRESTURL', {'cache': false}).success(function(data){
                $scope.product_list_2 = data;
            });
            $scope.results = MyService.doCalculation($scope.product_list_1, $scope.product_list_2);
        }
    }

In My markup I am calling it like

<button class="btn" ng-click="calculate(query)">Calculate</button>

As $http.get is asynchronous, I am not getting the data when passing in doCalculation method.

Any idea how can I implement multiple $http.get request and work like above implementation to pass both the response data into service?

Thanks in advance.

share|improve this question
    
I think you can chain promises – Ven Jun 10 '13 at 15:16
up vote 52 down vote accepted

What you need is $q.all.

Add $q to controller's dependencies, then try:

$scope.product_list_1 = $http.get('FIRSTRESTURL', {cache: false});
$scope.product_list_2 = $http.get('SECONDRESTURL', {'cache': false});

$q.all([$scope.product_list_1, $scope.product_list_2]).then(function(values) {
    $scope.results = MyService.doCalculation(values[0], values[1]);
});
share|improve this answer
    
I was going for nesting the promises but your solution is much better. – callmekatootie Jun 10 '13 at 15:35
1  
@jaux console.log($scope.product_list_1) should return the API response right?Getting "undefined". any clue? – mushfiq Jun 10 '13 at 16:00
    
@mushfiq I have updated my answer, give it a try. – Ye Liu Jun 10 '13 at 16:24
2  
@guiomie Is "q$" a typo? – Ye Liu Jul 29 '15 at 2:23
1  
how to handle errors in this case ? – AlainIb May 31 at 8:23

There's a simple and hacky way: Call the calculation in both callbacks. The first invocation (whichever comes first) sees incomplete data. It should do nothing but quickly exit. The second invocation sees both product lists and does the job.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.