Skip to content

Instantly share code, notes, and snippets.

@jonaszuberbuehler
Last active February 19, 2016 16:21
Show Gist options
  • Save jonaszuberbuehler/56da00e8578231189711 to your computer and use it in GitHub Desktop.
Save jonaszuberbuehler/56da00e8578231189711 to your computer and use it in GitHub Desktop.
http interceptor using angular-busy to show loading indicator
(function () {
'use strict';
angular
.module('app')
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('busyInterceptor');
}])
.factory('busyInterceptor', busyInterceptor);
busyInterceptor.$inject = ['$rootScope', '$q'];
function busyInterceptor($rootScope, $q) {
return {
request: onRequest,
response: onResponse,
responseError: onResponseError
};
function onResponseError(response) {
if (response.config && response.config.defer) {
response.config.defer.reject();
}
return $q.reject(response);
}
function onResponse(response) {
if (response.config && response.config.defer) {
response.config.defer.resolve();
}
return $q.when(response);
}
function onRequest(config) {
// filter for specific URLs only
if (config.url.indexOf('/api/') !== -1) {
registerPromise(config);
}
return $q.when(config);
}
function registerPromise(config) {
var defer = $q.defer();
$rootScope.activePromises.push(defer.promise);
config.defer = defer;
// once the promise is fulfilled we remove it from the activePromises array
defer.promise.finally(function () {
angular.forEach($rootScope.activePromises, function (promise, index) {
if (promise === defer.promise) {
$rootScope.activePromises.splice(index, 1);
}
});
});
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment