在多次调用 API 来获取同一 View 中所需的数据时,最好采取什么方法?
例如,您有多个选择框,需要包含从应用程序外部拉入的数据,所有这些都在同一 View 中。
有没有比简单地在 Controller 中一次性触发它们更优雅的解决方案?比如下面的
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);
})
});
等等...每个服务函数执行 $http.get 请求。
虽然这有效,但我觉得可能有一个更优雅的解决方案。
一如既往,我们非常感谢任何想法。
最佳答案
您可以使用q.all() ,因为它接受一系列 promise ,只有当所有 promise 都得到解决后,这些 promise 才会得到解决。
$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
关于javascript - Angular - 多个 $http.get 数据请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33423942/