Angular Interceptors
نویسنده: مسعود پاکدل
تاریخ: ۱۳۹۳/۰۶/۲۷ ۱۸:۲۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
module.factory('myInterceptor', ['$log', function($log) {
$log.debug('data');
var myInterceptor = {
....
....
....
};
return myInterceptor;
}]); module.factory('myInterceptor',['$q' , '$log', function($q , $log) {
$log.debug('data');
return {
request: function(config) {
return config || $q.when(config);
},
requestError: function(rejection) {
return $q.reject(rejection);
},
response: function(response) {
return response || $q.when(response);
},
responseError: function(rejection) {
return $q.reject(rejection);
}
}
}]); angular.module('myApp')
.config(function($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
}); .factory('httpInterceptor', function($q, $rootScope, $log) {
var numLoadings = 0;
return {
request: function(config) {
numLoadings++;
// Show loader
$rootScope.$broadcast("loader_show");
return config || $q.when(config);
},
response: function(response) {
if ((--numLoadings) === 0) {
// Hide loader
$rootScope.$broadcast("loader_hide");
}
return response || $q.when(response);
},
responseError: function(response) {
if (!(--numLoadings)) {
// Hide loader
$rootScope.$broadcast("loader_hide");
}
return $q.reject(response);
}
};
})
.config(function($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
}).directive("loader", function($rootScope) {
return function($scope, element, attrs) {
$scope.$on("loader_show", function() {
return element.show();
});
return $scope.$on("loader_hide", function() {
return element.hide();
});
};
}
); <div class="ajax-loader" loader>
<img src="@Links.Content.Images.loading_gif" />
</div> .ajax-loader {
position: absolute;
z-index: 100000;
display: none;
}