Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 20007

How to show loading icon for XHR requests?

I have a loading image that gets displayed on $routeChangeStart and is hidden once the route has changed. I'm trying to find something like this that can be used with xhrStart and xhrSuccess.

    $rootScope.$on('$routeChangeStart', function(){
        $rootScope.loading = true;
    });

    $rootScope.$on('$routeChangeSuccess', function(){
        $rootScope.loading = false;
    });

I know I can do this:

$rootScope.loading = true;
$http.get('/api/customers').success(function(data) {
   $rootScope.loading = false;
   ...

but that gets tedious.

Is there an XHR event in angularJS that can be used to show/hide the loading image?

Upvotes: 1

Views: 163

Answers (1)

Davin Tryon
Davin Tryon

Reputation: 67336

If the loading graphic is global, then you can solve this using an httpInterceptor. This is a naive implementation of an interceptor that toggles $rootScope.loading:

angular.module('myModule').factory('LoadingInterceptor', function ($rootScope) {

        $rootScope.loading = false;

        return {
            request: function (config) {
                $rootScope.loading = true;
                return config;
            },
            response: function (response) {
                $rootScope.loading = false;
                return response;
            }
        };
    })
    .config(function ($httpProvider) {
        $httpProvider.interceptors.push('LoadingInterceptor');
    });

Note: You may encounter issues with this naive implementation. For example you may have parallel XHR calls (and this implementation will cause the loader to flash). This is because when the first call response occurs $rootScope.loading is set back to false (even when the second call is still in progress).

Upvotes: 1

Related Questions