Utilizing a similar method to keep track of the number of requests sent that are awaiting response.
Implement an http-interceptor at the application level:
.config(['$httpProvider',
function($httpProvider) {
$httpProvider.interceptors.push('RequestCounterInterceptor');
}
])
The following is the code for the interceptor (can be customized to handle requests specifically to your API's URL):
.factory('RequestCounterInterceptor', ['RequestCounterService', '$q',
function(RequestCounterService, $q) {
return {
'request': function(request) {
RequestCounterService.increase();
return request;
},
'requestError': function(request) {
RequestCounterService.increase();
return $q.reject(request);
},
'response': function(response) {
RequestCounterService.decrease();
return response;
},
'responseError': function(response) {
RequestCounterService.decrease();
return $q.reject(response);
}
};
}
])
The service:
.service('RequestCounterService', ['$log',
function($log) {
var currentRequestCount = 0; // initialize
return {
increase: function() {
currentRequestCount++;
$log.log("currentRequestCount ", currentRequestCount);
},
decrease: function() {
currentRequestCount--;
$log.log("currentRequestCount ", currentRequestCount);
},
getCount: function() {
return currentRequestCount;
}
};
}
])
In any controller, directive, etc., you can utilize RequestCounterService.getCount()
to monitor how many requests have been sent without receiving a response yet. This information can be displayed to the user, such as
"There are currently XY requests being processed by the server."
If processing takes too long, it is advisable to address the issue on the server-side, as suggested by James Gaunt in the comments.