Using Interceptors in AngularJs

Posted By : Pulkit Chadha | 27-Sep-2017

Introduction:

The $http service helps us to communicate with the backend server and send  HTTP requests. 

Syntax:

var Interceptor = function ($q)  
{  
    return {  
        request: function (config)  
        {  
            return config;  
        },  
        requestError: function (rejection)  
        {  
            return $q.reject(rejection);  
        },  
        response: function (result)  
        {  
            return result;  
        },  
        responseError: function (response)  
        {  
            return $q.reject(response);  
        }  
    }  
}  
interceptorApp = angular.module('interceptorApp', []).config(function ($httpProvider)  
{  
    $httpProvider.interceptors.push(testInterceptor);  
});
        

An interceptor is a factory() service and we need to register our factory with the $httpProvider.There is 4 interceptor:

1)Request.
2)RequestError.
3)Response.
4)ResponseError.

1) Request:
Before sending the request to the server., request interceptor is called.
This takes only one argument i.e config obj and returns a config\ object.We can use request interceptor to add the authentication token to each HTTP request.

  request: function (config) {    
    var token = AuthenticationService.get("auth");    
    config.headers['x-Auth-token'] = token;    
    return config;    
}     
        

2)RequestError:
This interceptor is called when

any error is occurred in sending the request.We can use RequestError interceptor to keep the log of all the failed requests.

requestError: function (rejection) {      
    return $q.reject(rejection);    
}   
        

3)Response:

This interceptor is called after getting the response from the backend.We can use Response interceptor to add some extra keys in the response object.

response: function (obj) {    
     console.log('obj');    
	 obj.timestamp=Date.now();
     return obj;    
 },   

        

4)ResponseError:

This interceptor is called if an $http request fails.We can use ResponseError interceptor for global error handling or redirect a user to the login page if we get status code 401.

responseError: function (response) {    
  
     if (response.status === 401) {    
         $location.path('/signin');
         $flashService.showError = "Error occured";
     }    
  
     if (response.status === 500) {    
         $flashService.showError = "Error occured";    
         $location.path('/Error')    
     }    
     return $q.reject(response);    
 }  
        

About Author

Author Image
Pulkit Chadha

Pulkit is an expert web app developer and has good knowledge of JQuery, MongoDb, NodeJs, AngularJS, kaltura, Akamai. etc.

Request for Proposal

Name is required

Comment is required

Sending message..