http - Angularjs 多个 $http.get 请求

标签 http angularjs get

我需要执行两次 $http.get 调用,我需要将返回的响应数据发送到我的服务以进行进一步计算。

我想做如下的事情:

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 方法时没有获取数据。

知道如何实现多个 $http.get 请求并像上面的实现一样将响应数据传递到服务中吗?

最佳答案

你需要的是$q.all

$q 添加到 Controller 的依赖项中,然后尝试:

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

关于http - Angularjs 多个 $http.get 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17027196/

相关文章:

http - 保持事件标题说明

javascript - Promise.all 然后 (js)

javascript - 在 Typescript 中,Object.prototype 函数可以返回 Sub 类型实例吗?

html - 将 GET 方法返回的数据存储到变量中

c++ - HTTP GET请求问题

ios - 在 iPad 或 iPhone 上无需 UI 发送电子邮件的替代方法

HTTP HEAD 和 GET 不同的结果

node.js - 使用 Claudia-Api-Builder 为 AWS ApiGateway 设置 HTTP 选项响应

javascript - 如何在 AngularJS 中使用 MVC

javascript - Angular-UI-Bootstrap 和 UI-bootstrap