因为我使用的是 $http.ajax 请求。由于我对服务器的操作需要时间,因此需要很长时间。我需要在处理请求时显示加载程序,但加载程序不显示。虽然我的代码看起来是正确的。我尝试了不同的方法,但没有成功。
Index.html
<body ng-app="app">
<!-- loader, can be used on multiple pages-->
<div class="loading loader-quart" ng-show="isLoading"></div>
<!-- my logic -->
</body>
addCtrl.js
//method to get all the attributes and send to server using service
$scope.add = function () {
if ($scope.Option == 'newInstance')
$scope.singleObject.FK_Name = 'MetisEmptyTemplate';
$rootScope.isLoading = true;
var featuresList = websiteService.getUpdatedTree($scope.treeDataSource);
var formData = new Website("", $scope.singleObject.Name, $scope.singleObject.DisplayName, $scope.singleObject.Description, $scope.singleObject.State, "", $scope.singleObject.FK_Name, $scope.singleObject.Email, featuresList);
websiteService.addwebsite(formData);
$rootScope.isLoading = false;
}
websiteService.js
//service to add website
this.addwebsite = function (website) {
$http({
method: 'POST',
url: $rootScope.url + 'Add',
data: JSON.stringify(website),
contentType: 'application/json'
}).success(function (data) {
alert(data);
}).error(function (data, status, headers, config) {
//alert(data);
});
}
因为我要在开始时将 isLoading 设为“true”,然后在请求完成后将 isLoading 设为“false”。代码问题出在哪里?
最佳答案
您的 websiteServices 代码异步执行。这意味着上面的代码将显示加载器,然后立即再次隐藏它。
要在 Controller 中处理异步代码,您必须从服务返回一个 Promise,并使用 .then()
将微调器隐藏在回调函数中。
服务:
this.addwebsite = function (website) {
var deferred = $q.defer();
$http({
method: 'POST',
url: $rootScope.url + 'Add',
data: JSON.stringify(website),
contentType: 'application/json'
}).success(function (data) {
alert(data);
deferred.resolve(data);
}).error(function (data, status, headers, config) {
//alert(data);
deferred.reject(data);
});
return deferred.promise
}
Controller :
websiteService.addwebsite(formData).then(function(){
$rootScope.isLoading = false
});
关于javascript - 加载器未显示在 Angular js 中的 ajax 请求上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40019567/