【发布时间】:2016-02-29 22:11:53
【问题描述】:
我有 2 个 $http 函数,我使用 ng-init 调用它们,因为它们返回的数据会填充页面。
ng-init = "getOpen(); getClosed();"
这是最好的方法吗?
第一个函数;
$scope.getOpen = function () {
$http({
method: 'post',
url: "http://www.example.co.uk/php/open-get.php",
data: $.param({ 'location' : $scope.l,
'time' : $scope.t,
'day' : $scope.d,
'type' : 'get_restopen' }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).
success (function(data, status, headers, config){
if(data.success && !angular.isUndefined(data.data) ){
$scope.open = data.data;
} else {
$scope.open = [];
}
}).
error(function(data, status, headers, config) {
//$scope.messageFailure(data.message);
});
}
第二个功能;
$scope.getClosed = function () {
$http({
method: 'post',
url: "http://www.example.co.uk/php/closed-get.php",
data: $.param({ 'location' : $scope.l,
'time' : $scope.t,
'day' : $scope.d,
'type' : 'get_restopen' }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).
success (function(data, status, headers, config){
if(data.success && !angular.isUndefined(data.data) ){
$scope.closed = data.data;
} else {
$scope.closed = [];
}
}).
error(function(data, status, headers, config) {
//$scope.messageFailure(data.message);
});
}
一切都很好。我的问题是我猜这是在 AngularJS 中做事的一种有效方式吗?我是 Angular 新手,所以只是寻求指导。
1 - 我的$http 是否同时执行?还是一个在另一个开始之前完成?
2 - 是否需要在我的代码中引入$q 或promises?功能相互独立
3 - 无论成功与否,我如何检测所有 $http 请求何时完成
下面的代码正确吗?
$q.all([$scope.getOpen, $scope.getClosed]).then(function() {
//Both requests have been completed and I shall now set a bolean
$scope.compelete = true;
});
【问题讨论】:
-
我只想要快速/高效的执行,就是这样
标签: javascript angularjs