javascript – How to execute certain code every time a HTTP (ajax) transaction starts and ends?

Question:

I am developing an application with AngularJS and I need to define a hook ( handler ) that executes before and after each ajax transaction made with the $http object. I have seen that for jQuery there are ajaxStart and ajaxStop methods, but they obviously don't work in this case. Is there a direct equivalent, or can the same effect be achieved in some way, in AngularJS? The documentation doesn't seem to mention anything about it.

Note that I want the code to run for all transactions, not a specific one (in which case I would include the code in the .then delegates).

Answer:

As @rnrneverdies says you can use the $ interceptor.

What is the $ interceptor?

The $httpProvider contains an array of interceptors, an interceptor is a simple factory service that is in charge of intercepting the request, either when it is starting (Doing an Ajax Start), when it is returning the response (Ajax Stop) or when it fails, this helps us to handle errors or process something before / after the request. one of the ways to create it is as follows:

You create a Service factory

app.factory('HttpInterceptor',['$q','$rootScope','$injector',
    function($q, $rootScope, $injector) {
            return {
                    'request' : function(config) {
                                config.headers['X-Auth-Token'] = $rootScope.token;
                                config.headers['test_Auth-Token'] = $rootScope.token;
                                config.headers['Cache-Control'] = 'no-cache, no-store, max-age=0, must-revalidate';
                                // do something on success
                                return config;
                    },
                    'requestError' : function(rejection) {
                                        console.log("Ejecutando el 'requestError' de interceptor <<");
                                        return $q.reject(rejection);
                    },
                    'response' : function(response) {
                                        return response;
                    },
                    'responseError' : function(rejection) {
                                        if (rejection.status === 401) {
                                            console.log("Response Error 401",
                                                    rejection);
                                        }
                      console.log(">>> Falle <<");
                        return $q.reject(rejection);
                    }
}}]);

Note:

The methods that you see at the top such as 'request' , 'responseError' among others is the way in which Angular captures what is making the request (request) or what is giving an error. As you can see there are only those 4 methods according to the documentation .

How do I summon my interceptor?

You only need in an app.js or where your module is, create the angular config and call $httpProvider.interceptors like this:

app.config(['$routeProvider','$locationProvider','$httpProvider',
    function($routeProvider, $locationProvider, $httpProvider) {
          $httpProvider.interceptors.push('sacgHttpInterceptor');
     //Codigo demo no completo faltan los tags de cierre
Scroll to Top