Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shamsher31/483b3e74f34240b83d45 to your computer and use it in GitHub Desktop.
Save shamsher31/483b3e74f34240b83d45 to your computer and use it in GitHub Desktop.
Show Ionic Loading popup on each Angular http request
// For more details refere http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/
angular.module('MyApp', [])
// Custome Interceptor that will get injected on each HTTP request
// Add $ionicLoading at run time using $injector to avoid circular dependency error
.factory('customeInterceptor',['$timeout','$injector', '$q',function($timeout, $injector, $q) {
var requestInitiated;
function showLoadingText() {
$injector.get("$ionicLoading").show({
template: 'Loading...',
animation: 'fade-in',
showBackdrop: true
});
};
function hideLoadingText(){
$injector.get("$ionicLoading").hide();
};
return {
request : function(config) {
requestInitiated = true;
showLoadingText();
console.log('Request Initiated with interceptor');
return config;
},
response : function(response) {
requestInitiated = false;
// Show delay of 300ms so the popup will not appear for multiple http request
$timeout(function() {
if(requestInitiated) return;
hideLoadingText();
console.log('Response received with interceptor');
},300);
return response;
},
requestError : function (err) {
hideLoadingText();
console.log('Request Error logging via interceptor');
return err;
},
responseError : function (err) {
hideLoadingText();
console.log('Response error via interceptor');
return $q.reject(err);
}
}
}]);
.config(function ($urlRouterProvider,$httpProvider) {
$httpProvider.interceptors.push('customeInterceptor');
$urlRouterProvider.otherwise('/');
}
@petruisfan
Copy link

There is a bower component for that: https://github.com/petruisfan/ionic-ajax-interceptor

@dtelaroli
Copy link

dtelaroli commented Mar 1, 2017

I added verification to escape loading html templates at line 25:

if(config.url.endsWith('.html')) {
        console.log('Request html');
      } else {
        requestInitiated = true;
        showLoadingText();
        console.log('Request Initiated with interceptor');
      }
      return config;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment