Skip to content

Instantly share code, notes, and snippets.

@danielpereirabp
Forked from jonaszuberbuehler/busy.interceptor.js
Created February 19, 2016 16:21
Show Gist options
  • Save danielpereirabp/23608a197d8b4509e820 to your computer and use it in GitHub Desktop.
Save danielpereirabp/23608a197d8b4509e820 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