Angularjs 多个 $http.get 请求 [英] Angularjs multiple $http.get request
本文介绍了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.
我想做如下事情:
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>
由于 $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屋!
查看全文