Implementing an interceptor to display a loader while making API calls can come with its challenges. In this case, two API requests are set at intervals of every 60 seconds using $interval
. When the page is in focus, the loader functions correctly by showing up when a request is made.
However, a problem arises when a request is made while the tab is not in focus. The loader gets enabled but fails to disable. Even though {{show_loader1}}
reflects as false, it does not update ng-class accordingly.
The interceptor code in app.config is as follows:
$httpProvider.interceptors.push(function($q,$rootScope) {
return {
'request': function(config) {
$rootScope.loaders1++;
console.log('requestStart', $rootScope.loaders1);
if ($rootScope.loaders1 > 0) {
$rootScope.show_loader1 = true;
}
if(!$rootScope.$$phase) {
console.log("Applying root scope from requestStart");
$rootScope.$apply();
}
return config;
},
'response': function(response) {
$rootScope.loaders1--;
console.log('requestComplete', $rootScope.loaders1);
if ($rootScope.loaders1 <= 0) {
$rootScope.show_loader1 = false;
}
if(!$rootScope.$$phase) {
console.log("Applying root scope from request End");
$rootScope.$apply();
}
return response;
}
};
});
The corresponding HTML code is structured as follows:
<div class="butterbar" ng-class="{active:show_loader1,'hide':!show_loader1}"><span class="bar"></span></div>
When looking at the console output, you will see a series of timestamps alongside the loading progress and completion indicators for each request made.