Skip to content

Instantly share code, notes, and snippets.

@legend80s
Last active November 19, 2020 17:21
Show Gist options
  • Save legend80s/40365b765c04fce5fae014a1d97f1758 to your computer and use it in GitHub Desktop.
Save legend80s/40365b765c04fce5fae014a1d97f1758 to your computer and use it in GitHub Desktop.
Show spinner for you every pending HTTP requests
import angular from 'angular';
import 'angular-spinner';
function loadingInterceptor($q, $injector) {
let http;
let usSpinnerService;
let timeout;
return {
request(config) {
// console.log('request config:', config);
if (config.ignoreLoadingIndicator === true || config.url.endsWith('.html')) {
return config;
}
usSpinnerService = usSpinnerService || $injector.get('usSpinnerService');
timeout = timeout || $injector.get('$timeout');
timeout(() => {
console.log('Start spinner for', config.method, config.url);
usSpinnerService.spin('spinner-1');
});
return config;
},
response(response) {
// console.log('response:', response);
if (response.config.ignoreLoadingIndicator === true || response.config.url.endsWith('.html')) {
return response;
}
http = http || $injector.get('$http');
usSpinnerService = usSpinnerService || $injector.get('usSpinnerService');
timeout = timeout || $injector.get('$timeout');
// console.log('$http.pendingRequests.length:', http.pendingRequests.length);
if (http.pendingRequests.length === 0) {
timeout(() => {
console.log('Stop spinner for', response.config.method, response.config.url);
usSpinnerService.stop('spinner-1');
});
}
return response;
},
responseError(response) {
// console.log('response:', response);
if (response.config.ignoreLoadingIndicator === true || response.config.url.endsWith('.html')) {
return response;
}
http = http || $injector.get('$http');
usSpinnerService = usSpinnerService || $injector.get('usSpinnerService');
// console.log('error $http.pendingRequests.length:', http.pendingRequests.length);
if (http.pendingRequests.length === 0) {
timeout(() => {
// console.log('stop spinner for', response.config.method, response.config.url);
usSpinnerService.stop('spinner-1');
});
}
return $q.reject(response);
},
};
}
loadingInterceptor.$inject = ['$q', '$injector'];
function osLoadingIndicator() {
return {
scope: {
options: '=?',
},
template: '<span us-spinner="options" spinner-key="spinner-1"></span>',
link(scope) {
if (!scope.options) {
scope.options = { radius: 20, width: 4, length: 12, lines: 13 };
}
},
};
}
const app = angular.module('os-loading-indicator', ['angularSpinner'])
.factory('loadingInterceptor', loadingInterceptor)
.config(['$httpProvider', ($httpProvider) => {
$httpProvider.interceptors.push(loadingInterceptor.name);
}])
.directive('osLoadingIndicator', osLoadingIndicator);
export default app.name;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment