Using AngularJS 1.2
My interceptor looks like this:
$httpProvider.interceptors.push(['$q', '$log', '$rootScope', function ($q, $log, $rootScope) {
return {
'request': function(config) {
$rootScope.$broadcast('spin');
console.info('request!');
return config || $q.when(config);
},
...
In my nav controller (which handles and binds the loader/spinner to the view):
$rootScope.$watch('spin', function(event) {
console.info('spin');
$scope.spinner++;
});
The broadcast seems to happen only once at the end of all the responses received, even though I can see many request! in the console log.
How must I manage my global spinner/loader?
EDIT I wish to show a loader/spinner in my navbar whenever data is being loaded.
HTTP Interceptors is a special type of angular service that we can implement. It's used to apply custom logic to the central point between the client-side and server-side outgoing/incoming HTTP request and response. Keep in mind that the interceptor wants only HTTP requests.
A request interceptor is a piece of code that gets activated for every single HTTP request received by your application. Interceptors are very useful when you need to perform some common processing for every HTTP request.
The $watch
function doesn't listen for broadcast messages. It watches for changes on the scope. In this case, you are calling a function whenever $rootScope.spin
changes, which gets called (by default) immediately, which is why you got called once.
The $on
function is what you want here, as it is what will listen to broadcast events.
$rootScope.$on('spin', function(msg, data) {
console.info('spin');
$scope.spinner++;
});
I've put together a complete working example if you are curious:
http://codepen.io/BrianGenisio/pen/wIBHz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With