AngularJS HTTP interceptor

Hi Guys,

You can create interceptor on client side using AngularJS. AngularJS provide $httpProvider to change the default behavior of the $http service.

It has property interceptor which has array containing service factories for all synchronous or asynchronous $http pre-processing of request or post-processing of responses.

These service factories are ordered by request, i.e. they are applied in the same order as the array, on request, but reverse order, on response.

For reference you can visit below AngularJS documentation
https://docs.angularjs.org/api/ng/provider/$httpProvider
https://docs.angularjs.org/api/ng/service/$http#interceptors

Below is interceptor implementation.

index.html
<html ng-app="simpleDirective">
<head>
<script src="angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="DemoController">
<h2>AngularJS Interceptor Example</h2>
<div ng-repeat="msg in message">
 <div style="padding:5px;background:lightgrey;border:1px solid black;margin-bottom:10px;">{{msg}}</div>
</div>
</div>
</body>
</html>
app.js
var app = angular.module('simpleDirective', []);

app.config(['$httpProvider', function($httpProvider){
 $httpProvider.interceptors.push('httpInterceptor');
}]);

app.controller("DemoController", ['$rootScope','demoService', function($rootScope, demoService){
 $rootScope.message = [];
 $rootScope.message.push("In Demo Controller");
 demoService.functionOne();
}]);

app.service("demoService", ['$http','$rootScope',function($http, $rootScope){
 this.functionOne = function(){
  $http.get("temp.html")
  .success(function(data){
   $rootScope.message.push(data);
  })
  .error(function(data){
   $rootScope.message.push("Demo Service Error: "+data);
  });
 }
}]);

app.factory("httpInterceptor", function(){
  return{
    'request': function(config) {
      console.log("request");
      return config;
    },

   'requestError': function(rejection) {
      console.log("request error");
      return "Request error";
    },

    'response': function(response) {
      console.log("response");
      return response;
    },

   'responseError': function(rejection) {
      console.log("response error");
      return "response error";
    }
  }
 
});




Plunkr: https://plnkr.co/edit/hmdhdglgXw72Nh0XsjdC?p=preview

Good Day :)

Post a Comment

0 Comments