Ivan Proskuryakov
Ivan Proskuryakov

Reputation: 1742

How can I set global preloader in Angular App, while ajax data being loaded

I have Angular app and backend that returns json encoded data. I use this pattern for my app, when I get pages, categories and other data. During the data is loaded, app shows empty space, I want to set a global preloader which would be shown when I load json.

        getPage: function($id) {
            var url = API_URL+'/page/view/'+$id+'.json';
            console.log(url);
            return $http.get(url);
        }

Upvotes: 0

Views: 268

Answers (2)

Kent Aguilar
Kent Aguilar

Reputation: 5368

Try this:

<h1 ng-show="loadingCount > 0">Loading...</h1>

Your JS:

var app = angular.module('app', [])
            .config(httpInterceptorConfig)
            .factory('loadingDialogInterceptor', loadingDialogInterceptor);

//create interceptor
loadingDialogInterceptor.$inject = ['$q', '$rootScope'];

function loadingDialogInterceptor($q, $rootScope) {
    $rootScope.loadingCount = 0;

    function showLoading() {
        $rootScope.loadingCount++;
    }

    function hideLoading() {
        if ($rootScope.loadingCount > 0) {
            $rootScope.loadingCount--;
        }
    }

    return {
        request: function (config) {
            showLoading();
            return config || $q.when(config);
        },
        response: function(response) {
            hideLoading();

            return response || $q.when(response);
        },
        responseError: function(response) {
            hideLoading();

            return $q.reject(response);
        }
    };
}

//registers interceptor
httpInterceptorConfig.$inject = ['$httpProvider'];

function httpInterceptorConfig($httpProvider) {
    $httpProvider.interceptors.push('loadingDialogInterceptor');
}

Upvotes: 0

Jorge Guerola
Jorge Guerola

Reputation: 2082

Im using same architecture and i use interceptor for that:

angular.module('app',[]).config(function($httpProvider){

    $httpProvider.interceptors.push(function($q) {
      return {
       'request': function(config) {

        },

       'response': function(response) {
           // success
           return response || $q.when(response);
        },
        'responseError': function(rejection) {
         // error

           return $q.reject(rejection);
         }
      };
    });
});

With that you can handle your server calls. I hope will helps you

Upvotes: 1

Related Questions