Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I broadcast from the http interceptor?

Tags:

angularjs

q

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.

like image 545
Tjorriemorrie Avatar asked Aug 28 '13 09:08

Tjorriemorrie


People also ask

How do you use HTTP interceptors?

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.

What is HTTP request interceptor?

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.


1 Answers

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

like image 98
Brian Genisio Avatar answered Nov 15 '22 08:11

Brian Genisio