Is there a better way to sharing variables between a service and intercepting function in $httpProvider.interceptors?

43 views
Skip to first unread message

Trinh Ho

unread,
Jun 12, 2013, 9:30:48 AM6/12/13
to ang...@googlegroups.com
Hi, 

I want to create a service that tracks of the number of http requests and responses using the '$httpProvider.interceptors'. Please see the following code. I had to wrap it within a closure to hide "activeHttpRequestCount" from the global scope and expose it only through the httpInterceptorService.

This code works exactly what I need, but I would like to know if there's a more elegant solution to sharing variables between a service and the intercepting function that i'm passing into $httpProvider.interceptors.

 
var myApp= angular.module('myApp', []);
 
(function () {
    var activeHttpRequestCount = 0;
    myApp.service('httpInterceptorService', function () {
        return {
            getActiveRequestCount: function () {
                return activeHttpRequestCount;
            }
        };
    }).config(['$httpProvider',
            function ($httpProvider) {
                $httpProvider.interceptors.push(function ($q) {
                    return {
                        request: function (config) {
                            activeHttpRequestCount++;
                            return config;
                        },
                        response: function (response) {
                            activeHttpRequestCount--;
                            return response;
                        }
                    };
                });
            }
    ]);
})();


Thanks,
-Trinh 

Andy Joslin

unread,
Jun 12, 2013, 4:47:10 PM6/12/13
to ang...@googlegroups.com
You could inject your service into the interceptor (where you currently inject $q) and call something like `httpInterceptorService.addRequest()` there.

Trinh Ho

unread,
Jun 13, 2013, 8:23:00 PM6/13/13
to ang...@googlegroups.com
Works exactly as intended,  but do you know how to do this and survive minification? Do I have to use the $injector explicitly?  
Reply all
Reply to author
Forward
0 new messages