gpt4 book ai didi

javascript - 使用多个 ajax 请求初始化 Controller 的最佳方法

转载 作者:行者123 更新时间:2023-12-03 08:15:46 25 4
gpt4 key购买 nike

我有 2 个使用 ng-init 调用的 $http 函数,因为它们返回的数据会填充页面。

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 - 是否需要在我的代码中引入 $qpromises ?功能相互独立

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;
});

最佳答案

  1. 假设您自己在某处调用这两个方法,是的。 $http 调用默认是异步的

  2. 已经完成,$http 实际上返回了一个 Promise!

  3. promise.all() 是一种优雅的方法,无需修改 Promise 的返回值即可实现此目的。它实际上是一个完成观察者。更多详细信息请参见 promise reference

关于javascript - 使用多个 ajax 请求初始化 Controller 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33945001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com