Angularjs multiple $http.get request

别等时光非礼了梦想. 提交于 2019-12-04 07:28:54

问题


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?


回答1:


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]);
});



回答2:


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.




回答3:


I had a similar problem recently so I'm going to post my answer also:

In your case you only have two calculations and it seems to be the case this number is not mutable.

But hey, this could be any case with two or more requests being triggered at once.

So, considering two or more cases, this is how I would implement:

var requests = [];
requests.push($http.get('FIRSTRESTURL', {'cache': false}));
requests.push($http.get('SECONDRESTURL', {'cache': false}));

$q.all(requests).then(function (responses) {
  var values = [];
  for (var x in responses) {
    responses[x].success(function(data){
      values.push(data);
    });
  }
  $scope.results = MyService.doCalculation(values);
});

Which, in this case, would force doCalculation to accept an array instead.



来源:https://stackoverflow.com/questions/17027196/angularjs-multiple-http-get-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!