Monday 6 June 2016

Usage of Interceptors in Angular js

Interceptors In Angular js :
**************************
In this post we are going to see about the interceptors present in the angular js. using angular js we can make a call to the service which will communicate to the DB server and return the response data from the service layer.Now where this interceptors will come to play a role.

To make a Call to service we have to use the $http service which is used to communicate the service layer through the REST call.

Example:

    function validateLogin(userdetails) {
        return $http({
            url: 'api/Login',
            method: 'POST',
            data: {
                UserName: userdetails.email,
                Password: userdetails.password,
                RememberMe: userdetails.remember
            }
        });
    }



From the example you can see that the validate the login credentials take place by service call to the url  api/Login through POST call.

Sometimes there is a scenario where we want to do some logic or some logical changes before the request to the server and after the response from the server. For example if we want to track the time taken for each request and response, Then how we can do that to be possible.

Mostly common thing many of them doing will be make a note in time  before the request and after the response for Each Request.In this scenario the code is duplicate in many places.

Now how we can reduce the redundant code and make our case possible ?
In this scenario Interceptors are comes to play there role. Interceptors are used to inject the code which will make a call before the Request and after response from the $http. To use this we have to do the following steps.

Sometimes we need to modify the outgoing requests for adding the session Token information in the request header to the server for validation.. This kind of scenario's also can be done using interceptors.

Step 1 :
**********
var mainApp = angular.module('mainApp', []);

Step 2:
**********
Add the interceptors to the $httpProvider, Here we are adding the RequestTracker to the interceptor.

mainApp.config(['$httpProvider'function ($httpProvider) {
    $httpProvider.interceptors.push('RequestTracker');

}]);


Step 3:
***********
Define the RequestTracker which will have a common structure to inject a call, four common methods that we can inject for a $http service is response, request, requestError, responseError


mainApp.factory('RequestTracker'function () {

    var _interceptors = {

        request: function (config) { },
        response: function (response) { },
        requestError: function (requestReject) { },
        responseError: function (response) { }

    };

    return _interceptors;

});

From the structure you can see that the four methods that can be inject in to $http service.

request is the method is used to add a additional code before the service call,
response is the method which is used to add the code to the response data.

remaining two methods will call at the Error time before the Request and Response.

Example:
************

var mainApp = angular.module('mainApp', []);


mainApp.config(['$httpProvider'function ($httpProvider) {
    $httpProvider.interceptors.push('RequestTracker');
}]);


mainApp.factory('RequestTracker'function (sessionFactory,$q) {

    var _interceptors = {

        request: function (config) {
               
             /* Session token send from client */
            config.headers['sessiontoken'] = sessionFactory.token;             
            
             /* time track for reach request */
             config.requestTime = new Date().getTime();    

            return config;
        },
        response: function (response) {
            
           /* Response time for each request */      
            response.config.responseTime = new Date().getTime(); 
            response.config.timeTaken = response.config.responseTime -                                                               response.config.requestTime;
            return response;
        },
        requestError: function (requestReject) { },
        responseError: function (response) { }

    };

    return _interceptors;
});



Before Interceptors for Request 
*******************************
{
    "transformRequest": [
        null
    ],
    "transformResponse": [
        null
    ],
    "method""GET",
    "url""https://sample/api/Login
    "headers": {
        "Accept""application/json, text/plain, */*"
    }
}


After Interceptors for Request 
********************************
{
    "transformRequest": [
        null
    ],
    "transformResponse": [
        null
    ],
    "method""GET",
    "url""https://sample/api/Login
    "headers": {
        "Accept""application/json, text/plain, */*",
        "sessiontoken":23443242342423432
    },
    "requestTime":1431451831775

}


Now we can see how to handle the requestError and responseError in interceptors.


Now whenever the session token is empty we have to redirect to a new service call, where we can refresh and taken the new token, i.e redirect to new service API call in request Error at whenever the requestReject have particular code.




mainApp.factory('RequestTracker'function (sessionFactory,$q) {

    var _interceptors = {

        request: function (config) {
            
              if (sessionFactory.token != "") {
               
                /* Session token send from client */
                config.headers['sessiontoken'] = sessionFactory.token; 
                /* time track for reach request */
                config.requestTime = new Date().getTime();     

                return config;
            }
            else {
                return $q.reject('sessionInvalid');
            }
        },
        response: function (response) {
            /* Response time for each request */
            response.config.responseTime = new Date().getTime(); 
            response.config.timeTaken = response.config.responseTime -                                                              response.config.requestTime;
            return response;
        },
        requestError: function (requestReject) {

            if (requestReject == "sessionInvalid") {

                var newrequest = {
                    transformRequest: [],
                    transformResponse: [],
                    method: "POST",
                    url: "api/tokenRefresh",
                    headers: {
                        Accept: "application/json, text/plain, */*",
                        sessiontoken: "RefreshToken"
                    }
                };

                return newrequest;

            } else {
                return $q.reject(requestReject);
            }
        },
        responseError: function (response) {


        }

    };

    return _interceptors;
});



From this post you can see how to use the interceptors in the real time service call to the DB layer.


No comments:

Post a Comment