Angular js - detect when all $http() have finished

后端 未结 3 1434
一生所求
一生所求 2020-12-12 19:47

Ok i have tons of $http() calls all around the app code,

i\'m wondering is there any way / best practice to detect when all $http() around

3条回答
  •  情书的邮戳
    2020-12-12 20:01

    Do it like this:

    angular.module('app').factory('httpInterceptor', ['$q', '$rootScope',
        function ($q, $rootScope) {
            var loadingCount = 0;
    
            return {
                request: function (config) {
                    if(++loadingCount === 1) $rootScope.$broadcast('loading:progress');
                    return config || $q.when(config);
                },
    
                response: function (response) {
                    if(--loadingCount === 0) $rootScope.$broadcast('loading:finish');
                    return response || $q.when(response);
                },
    
                responseError: function (response) {
                    if(--loadingCount === 0) $rootScope.$broadcast('loading:finish');
                    return $q.reject(response);
                }
            };
        }
    ]).config(['$httpProvider', function ($httpProvider) {
        $httpProvider.interceptors.push('httpInterceptor');
    }]);
    

    Then use event bound to $rootScope anywhere (preferable to use in directive):

    $rootScope.$on('loading:progress', function (){
        // show loading gif
    });
    
    $rootScope.$on('loading:finish', function (){
        // hide loading gif
    });
    

提交回复
热议问题