Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs multiple $http.get request

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?

like image 482
mushfiq Avatar asked Jun 10 '13 15:06

mushfiq


1 Answers

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]); }); 
like image 62
Ye Liu Avatar answered Sep 19 '22 18:09

Ye Liu