Monday, 29 January 2018

HTTP Interceptors In AngularJS

In a request and response communication of a HTTP call if we want to inject some custom logic the HTTP Interceptor comes into picture. HTTP Interceptors executes some custom logic before or after the HTTP call.



For example, appending the authentication token to every HTTP request and that token is generated from the client who needs to be validated at the server for security purpose.

These interceptors act as a hook up for the HTTP calls.

HTTP Interceptors are used for adding custom logic for authentication, authorization, session/state management, logging, modifying Response, URL rewriting, Error handling, Caching, adding custom header, timestamp in the request /response, encrypt and decrypt the request and response information or manipulate the request and response data over the request cycles.

HTTP Interceptors are similar to custom HTTP Module of ASP.NET.

There are four kinds of interceptors in AngularJS - Request, requestError, response, responseError

Setup
function testInterceptor() {
  return {
    request: function(config) {
      return config;
    },

    requestError: function(config) {
      return config;
    },

    response: function(res) {
      return res;
    },

    responseError: function(res) {
      return res;
    }
  }
}

angular.module('app', [])
.factory('testInterceptor', testInterceptor)
.config(function($httpProvider) {
  $httpProvider.interceptors.push('testInterceptor');
})
.run(function($http) {
  $http.get('http://test-routes.herokuapp.com/test/hello')
    .then(function(res) {
      console.log(res.data.message)
    })
})


<html>
    <head>
        <title>$http interceptors</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script>
        <script src="app.js"></script>
    </head>
    <body ng-app="app">
    </body>
</html>

An interceptor is simply a factory() service that returns an object with 4 properties that map to functions:

request: called before a request is sent, capable of mutating the request object
requestError: 
response: called with an $http request succeeds, is passed the results object,
responseError: called if an $http method fails

This object is then registered as an interceptor with the $httpProvider in a config() block. It's perfectly fine to include all or only a subset of the properties that are needed.

The way to think about interceptor functions is as promise callback functions that are called for all HTTP requests.


Continue Reading →

PreLink, PostLink and Controller Methods of Angular Directives

PreLink, PostLink and Controller Methods of Angular Directives

Link function of an Angular Directive
As the name implicates, the link function has the duty of linking the model to the templates. Link function is the place where AngularJs does the data binding to the compiled templates. Let’s take a look at the signature of a link function.

link: function LinkFn(scope, elem, attr, ctrl){}

There are 4 parameters available to the link function.

scope : The scope of the directive
elem : Dom element where the directive is applied
attr : Collection of attributes of the Dom Element
ctrl : Array of controllers required by the directive

Now let’s create a simple directive to see how the data binding works.

var app = angular.module('app', []);
app.directive('dad', function () {
    return {
        restrict: 'EA',
        template: '<div>{{greeting}}{{name}}</div>',
        link: function(scope,elem,attr){
            scope.name = 'Paul';
            scope.greeting = 'Hey, I am ';
        }
    };
});

<div ng-app="app">
    <dad></dad>
</div>

The name and greeting properties attached to the scope are linked to the template once the link function is executed. And, the browser will show “Hey, I am Paul” in the view.

The above is the usual way to create a link function inside a directive. However, AngularJs allows to set the link property to an object also. Advantage of having an object is, we can split the link function into two separate methods called, pre-link and post-link.

Both Pre & Post link functions have the same syntax as defined below but the only difference is the order in which they get executed.

Pre-linking 
function Executed before the child elements are linked. Not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking.

Post-linking function Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.

Lets start by defining a simple directive

var mod = angular.module('Mod', []);
           mod.directive('myDir'function () {
               return {
                   restrict: 'E',
                   controller: function ($scope, $element) {
                       console.log(': controller');
                       console.log($element.html());
                   },
                   compile: function (tElem, tAttrs) {
                       console.log(': compile');
                       console.log(tElem.html());
                       return {
                           pre: function (scope, iElem, iAttrs) {
                               console.log(': pre link');
                               console.log(iElem.html());
                           },
                           post: function (scope, iElem, iAttrs) {
                               console.log(': post link');
                               console.log(iElem.html());
                           }
                       }
                   }
               }
           });


Let’s use it in our html code like this

<my-dir>
     Parent
     <my-dir>Child</my-dir>
</my-dir>

Above we have defined a very simple directive using all important functions of a directive. We have nested that directly in itself and added parent/child text in the template. Now if we see the output we know the order in which these directives get executed.

: compile
Parent
<my-dir>Child</my-dir>
: compile
Child
: controller
Parent
<my-dir>Child</my-dir>
: pre link
Parent
<my-dir>Child</my-dir>
: controller
Child
: pre link
Child
: post link
Child
: post link
Parent
<my-dir>Child</my-dir>

Looking at the above we can see the order in which these functions execute. This order is always very important, the reason we will see later.

So to conclude the order is:
Compile Parent -> Compile Child -> Controller Parent -> PreLink Parent -> Controller Child -> PreLink Child -> Post Link Child -> Post Link Parent


Continue Reading →

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)