Angularjs多个$ http.get要求 [英] Angularjs multiple $http.get request

查看:220
本文介绍了Angularjs多个$ http.get要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要做两$ http.get电话,我需要返回的响应数据发送到我的服务做进一步的计算。

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

在我的标记,我叫它像

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

由于$ http.get是异步的,我没有得到传递doCalculation方法时的数据。

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

任何想法,我怎么可以实现多个$ http.get请求,类似上面的实施工作,既响应数据传递到服务?

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

先谢谢了。

推荐答案

您需要的是 $ q.all

添加 $ Q 来控制的依赖,然后尝试:

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

这篇关于Angularjs多个$ http.get要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆