更新时间:2023-11-21 17:18:46
做这样的:
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');
}]);
然后使用绑定到 $ rootScope
事件的任何地方(preferable指令中使用):
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
});