-
-
Save danielpereirabp/23608a197d8b4509e820 to your computer and use it in GitHub Desktop.
http interceptor using angular-busy to show loading indicator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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