Skip to content

Instantly share code, notes, and snippets.

@prayagverma
Forked from jintoppy/GlobalAjaxInterceptor
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prayagverma/b4ac6539ae5e8993d24f to your computer and use it in GitHub Desktop.
Save prayagverma/b4ac6539ae5e8993d24f to your computer and use it in GitHub Desktop.
angular.module('globalmodule')
.config(['$provide', '$httpProvider', function($provide, $httpProvider){
$provide.factory('GlobalAjaxInterceptor', ['$q', '$rootScope', function($q, $rootScope){
var currentRequests={http: {}, ajax: {}};
function addHttpRequest(conf){
currentRequests.http[conf.url] = conf.promiseObj;
}
function addAjaxRequest(conf){
currentRequests.ajax[conf.url] = conf.promiseObj;
}
function abortAllHttpRequests(httpRequests){
angular.forEach(httpRequests, function(promise, url){
promise && promise.resolve();
});
}
function abortAllAjaxRequests(ajaxRequests){
angular.forEach(ajaxRequests, function(xhr, url){
xhr && xhr.abort();
});
}
function abortAllOldRequests(){
var oldRequests = angular.copy(currentRequests);
currentRequests = {
http: {},
ajax: {}
};
abortAllHttpRequests(oldRequests.http);
abortAllAjaxRequests(oldRequests.ajax);
}
$( document ).ajaxSend(function(event, xhr, options) {
addAjaxRequest({url: options.url, promiseObj: xhr});
});
$rootScope.$on('$stateChangeSuccess', function () {
abortAllOldRequests();
});
return {
// On request success
request: function (config) {
var deferred = $q.defer();
config.timeout = deferred.promise;
addHttpRequest({url: config.url, promiseObj: deferred});
return config;
},
// On request failure
requestError: function (rejection) {
// Return the promise rejection.
return $q.reject(rejection);
},
// On response success
response: function (response) {
// Return the response or promise.
return response || $q.when(response);
},
// On response failture
responseError: function (rejection) {
// Return the promise rejection.
return $q.reject(rejection);
}
};
}]);
$httpProvider.interceptors.push('GlobalAjaxInterceptor');
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment