[英]Multiple HTTP requests in Angular
所以这是我的控制器:
app.controller('dbCtrl', function($scope, $http) {
$http.get("http://private-abc.apiary-mock.com/bus")
.success(function(response) {
$scope.network = response.networkupdates;});
});
我接下来要做的是调用第二个HTTP请求,按照最佳实践,我猜想最好是创建一个第二个控制器来调用第二个HTTP,或者最好在当前控制器中包含第二个HTTP调用(如果是的话,如何?)谢谢。
因此,使用承诺的一个很酷的方面就是可以将它们链接在一起。 因此,就您而言,您正在打电话:
$http.get("http://private-abc.apiary-mock.com/bus")
它返回一个承诺,然后您可以将其链接到另一个承诺,如下所示:
var requests = $http.get("http://private-abc.apiary-mock.com/bus").then(function(response) {
$scope.network = response.networkupdates;
// make second get call and return it to chain the promises
return $http.get("some-other-endpoint").then(function(otherResponse) {
// you can do something here with the response data
return otherResponse;
});
});
您现在拥有的是两个链接的诺言,这些诺言将返回最终值,因此,如果稍后调用它:
requests.then(function(otherResponse) {
// or you can do something here
doSomething(otherResponse);
});
至于Angular的最佳实践,我想说您最好创建一个服务或工厂来处理所有HTTP请求。 控制器实际上只是用来将数据绑定到视图。 服务是应该进行业务逻辑和数据填充的地方。
您可以在同一控制器中进行$http
调用。
$http
服务是一个带有单个参数(配置对象)的函数,该参数用于生成HTTP请求,并通过两个$ http特定方法返回成功的promise
: success and error
。 它在内部使用$q
(受Kris Kowal Q启发的承诺/延期实现)。
如果两个$http
彼此独立,则可以使用$q.all
来“ $q.all
” http调用的结果。
范例:
$q.all([
$http.get("http://private-abc.apiary-mock.com/bus"),
$http.get('/someUrl')
]).then(function(results) {
$scope.network = results[0];
$scope.whatevername= results[1]
});
}
如果您的http调用相互依赖,则可以使用chaining
的概念。
例如:
$http.get("http://private-abc.apiary-mock.com/bus").then(function(result) {
$scope.network = result.networkupdates;
return $http.get("someurl").then(function(res) {
return res;
});
});
有关q
引用,请参见https://github.com/kriskowal/q
有关$q service
引用,请参见https://docs.angularjs.org/api/ng/service/ $ q
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.