Umar Umar - 1 month ago 9
Ajax Question

Loader not being shown on ajax request in angular js

Since I am using ajax request using $http. It takes a long time since my operation on server takes time. I need to show loader while processing request, but the loader does not show. Although my code seems correct. I tried different methods but did not work.

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


Since I am going to turn isLoading as "true" in start and then after request completes I turn isLoading "false". Where is the problem in code?

Answer

Your websiteServices code gets executed asynchronously. Which means that the above code would display the loader and then pretty much hide it again instantly.

To handle async code in the controller you must return a promise from the service and put the hiding of the spinner in a callback function using .then().

service:

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