-
Notifications
You must be signed in to change notification settings - Fork 11
busyInterceptor
busyInterceptor
is an $http
interceptor that registers itself when the module is loaded. No extra configuration is necessary or available.
It monitors when requests are issued through the $http
service. When a request is made, an internal counter is incremented and an event is broadcasted on the $rootScope
called busy.begin
. When the request is completed or rejected, the internal counter is decremented and busy.end
is broadcasted. Both events are provided an argument that contains info about the request that started or ended, and the state of the internal counter.
The following events are broadcast on the root scope:
-
busy.begin: One argument object
{url: string, name: string }
.url
is the URL of the request that was made.name
is the optional name provided in the config object passed to$http
when the request was made. The purpose ofname
is to identify the request so it can be filtered. This event indicates that an HTTP request was made, suggesting the app is busy. -
busy.end: One argument object
{url: string, name: string, remaining: integer }
.url
is the URL of the request that was made.name
is the optional name provided in the config object passed to$http
when the request was made. The purpose ofname
is to identify the request so it can be filtered.remaining
is the number of outstanding HTTP requests. This event indicates that an HTTP request has ended. Ifremaining
is zero, that means there are no outstanding requests and the application is effectively not busy.
If you do not want an event to raise either event, just specify notBusy:true
on the config object you pass to $http
and the interceptor will ignore it.
Example:
$http.get('/path', {notBusy:true}); // will not raise either event
You may wish to respond to busy events from certain URLs, or by arbitrary names that you tag each request with. By default, the interceptor will include the url
from the config. If you also specify name
, that will be available in the event arg, too. Just inspect those values in your event handler to do your filtering.
Example:
$scope.$on('busy.begin', function(evt, args) {
console.log('busy.begin from url: ' + args.url + ' name: ' + args.name);
});
$scope.$on('busy.end', function(evt, args) {
// filter by url and name
if (args.url == '/path') console.log('busy.end from /path!');
if (args.name == 'my-special-request') console.log('busy.end from my-special-request!');
// if all requests are complete, log it
if (args.remaining <= 0) console.log('all requests are complete');
});
// a function that issues a request and provides a name
$scope.test = function() {
$http.get('/path', {name: 'my-special-request'}); // incidentally, this will log all three busy.end events, since the URL and name will match, and it will be the only outstanding request
};