角 - 为数据的多个$ http.get请求 [英] Angular - Multiple $http.get Requests for Data
问题描述
什么是做多次调用时,一个API,在同一视图所需要的数据采取最好的方法?
例如,你有哪些需要包含数据的多个选择框从应用程序外拉,都在同样的观点。
有没有更优雅的解决方案不是简单地在你的控制器立即开除他们呢?如以下
app.controller('myCtrl',函数($服务){ $ service.getDataOne()。然后(功能(响应){
$ scope.dataOne =响应;
},功能(错误){
的console.log(错误);
}); $ service.getDataTwo()。然后(功能(响应){
$ scope.dataTwo =响应;
},功能(错误){
的console.log(错误);
})
});
等等......各项服务功能执行$ http.get要求。
虽然这个作品,我觉得有可能是一个更优雅的解决方案。
一如既往任何想法是非常AP preciated。
您可以使用 q.all(),因为它接受的承诺,当所有的承诺都得到了解决,将只得到解决的数组。
$ q.all([
$ service.getDataOne(),
$ service.getDataTwo()
])。然后(功能(数据){
$ scope.dataOne =数据[0];
$ scope.dataTwo =数据[1];
});
如果你看一下链接,
q.All()
在页面的最下方
块引用>What is the best approach to take when making multiple calls to an API for data needed in the same view?
For example, you have multiple select boxes which need to contain data pulled in from outside the app, all in the same view.
Is there a more elegant solution than simply firing them all at once in your controller? Such as the following
app.controller('myCtrl', function($service) { $service.getDataOne().then(function(response) { $scope.dataOne = response; }, function(error) { console.log(error); }); $service.getDataTwo().then(function(response) { $scope.dataTwo = response; }, function(error) { console.log(error); }) });
etc...with each service function performing a $http.get request.
While this works, I feel there is probably a more elegant solution.
Any thoughts as always is much appreciated.
解决方案You can use q.all(), as it accepts an array of promises that will only be resolved when all of the promises have been resolved.
$q.all([ $service.getDataOne(), $service.getDataTwo() ]).then(function(data){ $scope.dataOne = data[0]; $scope.dataTwo = data[1]; });
If you look at the link,
q.All()
is at the very bottom of the page
这篇关于角 - 为数据的多个$ http.get请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!