Step by step guide to use $http interceptor in AngularJS for intercepting each $http request

If you want to define some general rules for how your application process HTTP request and response you can use $http interceptors.

As name show something is there to intercept HTTP request on application end. So why we need this?

If you’re familiar with one page application development in AngularJs you must have requirement that show a pre loader whenever fetch data from database. So what you do? Write two functions to show and hide pre loader and write each request start and end. Ok fine. So in a bad day your Ajax request fails and you didn’t handle it properly and your page constantly showing pre loader.

This is very basic scenario which I have explained above and if you have complex one. You’re communicating with a Web Api sending and receiving data. Web Api required an authorization token in each request header. So what you do? Again write a function to insert token in each request and place it in every single $http request. Well you’re repeating yourself and being a developer it is very bad habit.

And what happened if you want to show some error page on 404, 401 something like that. You wire up your each $http request with duplicate code and response check status and show message. Well guys it is 2017 and you have no need to reinvent the wheel.

So Now what’s the solution of these kind of problems. AngularJs become very impressive features and $http interceptor is one of them. You can catch every request before sending it to server and check it after getting response from server.

Ok enough talk for today now lest start some actual implementation.

Interceptors Responses

So what functions we need to write down in interceptor angular factory?

  • request
  • response
  • requestError
  • responseError

Interceptors methods implementation

Below code demonstration is about to show a pre-loader on each HTTP request and show network error page on against different error codes return by server. You can get idea about it and implement it according to your requirement.

                   
 'use strict';
app.factory('authInterceptorService', ['$q', '$rootScope', function ($q,  $rootScope) {
                        var authInterceptorServiceFactory = {};
                                                                                                                                                                                               var activeRequests = 0;
    var started = function () {
        if (activeRequests == 0) {
            $rootScope.$broadcast('loadingStatusActive');
        }
        activeRequests++;
    };
    var ended = function () {
        activeRequests--;
        if (activeRequests == 0) {
            $rootScope.$broadcast('loadingStatusInactive');
        }
    };
    var _request = function (config) {
        started();
        return config;
    }
        var _response=function(config){
                  ended();
                return config;
        }
    var _responseError = function (rejection) {
        ended();
        if (rejection.status === 401) {
            $location.path('/login');
        } else if (rejection.status === 404) {
            $location.path('/NetworkError');
        }
        
        return $q.reject(rejection);
    }
    authInterceptorServiceFactory.request = _request;
    authInterceptorServiceFactory.responseError = _responseError;
    authInterceptorServiceFactory.response=_response;
return authInterceptorServiceFactory;
                    }]);

Hookup this factory in AngularJs App

Now open your main app file to register above factory.

                app.config(function ($routeProvider, $httpProvider, $locationProvider, $qProvider) {

                    //your existing logic

                    $httpProvider.interceptors.push('authInterceptorService');

                });

Custom Directive

I create a custom directive to show loading message. Below code is refer to Custom directive

                app.directive('loadingStatusMessage', function() {
    return {
        link: function($scope, $element, attrs) {
            var show = function() {
                $element.css('display', 'block');
            };
            var hide = function() {
                $element.css('display', 'none');
            };
            $scope.$on('loadingStatusActive', show);
            $scope.$on('loadingStatusInactive', hide);
            hide();
        }
    };
})

Register Directive

Now you need to select any preloader which you want to show and just a custom html attribute to it. in my case it is loadingStatusMessage

Result

You can see this magic in your browser and also can see in network tab that each request intercept in interceptor factory.