Detailed explanation of HTTP interception _angularjs in Angularjs

Source: Internet
Author: User

http interception , the $http service, allows us to interact with the server, and sometimes we want to do something before the request is made and after the response is received.
The $httpProvider contains an array of interceptors.

So we create a interceptor.

App.factory (' Myinterceptor ', [' $log ', function ($log) {
  $log. Debug (');
  
  var myinterceptor = {};
  
  return myinterceptor;
}])

Then register Interceptor.

App.config ([' $httpProvider ', function ($httpProvider) {
  $httpProvider. Interceptors.push (' Myinterceptor ');
}])
 

Here are some examples of $http interception.

Asynchronous operations in interceptors

App.factory (' Myinterceotpr ', ' Someasyncservcie ', function ($q, someasyncservcie) {
  var requestinterceptor = {
    Request:function (config) {
      var deferred =%q.defer ();
      Someasyncservice.doasyncoperation (). Then (function () {
        ...
        ). Deferred.resolve (config);
      }, Function () {
        ...
        Deferred.resolve (config);
      })
      return deferred.promise;
    }
  ;
  
  return requestinterceptor;
})

Above, is a request to intercept, do an asynchronous operation, according to the results of the asynchronous operation to update CONFIG.

Of course there is also response interception.

App.factory (' Myinterceptor ', [' $q ', ' Someasyncservice ', function ($q, someasyncsercice) {
  var responseinterceptor = {
    Response:function (response) {
      var deferred = $q. Defer ();
      Someasyncservice.doasyncoperation (). Then (function (response) {
        ...
        ) Deferred.resolve (response);
      }, Function (response) {
        ...
        Deferred.resolve (response);
      })
      return deferred.promise;
    }
  ;
  return responseinterceptor;
}])

Session Intercept, Request intercept

There are 2 types of authentication on the server, one based on cookies and one based on token. For token authentication, when the user logs in and gets a token from the server, the token is sent to the server on every request.

Create a injector about the session:

App.factory (' Sessioninjector ', [' Sessionservice ', function (sessionservice) {
  var sessioninjector = {
    request : function (config) {
      if (! sessionservice.isanonymous) {
        config.headers[' x-session-token '] = Sessionservice.token;
      }
      return config;
    }
  ;
  
  return sessioninjector;
}])

Visible, the token returned from the service side is placed in the config.headers.

Register INJECTOR:

App.config ([' $httpProvider ', function ($httpProvider) {
  $httpProvider. Interceptors.push (' Sessioninjector ');
}])

Issue a request:

$http. Get (');

Before interception is roughly:

{
  ' transformrequest ': [null],
  ' transformresponse ': [null],
  ' method ': ' Get ',
  ' url ': ',
  ' Headers ": {" Accept ":"
    Application/json, text/plain,*/* "
  }
}

After intercepting, there are two more x-session-token fields in the headers:

{
  ' transformrequest ': [null],
  ' transformresponse ': [null],
  ' method ': ' Get ',
  ' url ': ',
  ' Headers ": {" Accept ":"
    Application/json, text/plain,*/* ",
    " X-session-token ": ...
  }
}

Timestamp, request and response interception

App.factory (' timestampmarker ', [function () {
  var timestampmarker = {
    request:function (config)
      { Config.requesttimestamp = new Date (). GetTime ();
      return config;
    },
    response:function (response) {
      Response.config.responseTimestamp = new Date (). GetTime ();
      return config;
    }
  ;
  
  return timestampmarker;
}])

Above, intercept in requests and responses, assigning current time to Config.requesttimestamp and Config.responsetimestamp.

Register Interceptor:

App.config ([' $httpProvider ', function ($httpProvider) {
  $httpProvider. Interceptors.push (' Timestampmarker ');
}])
 

Then you can work out the time it takes to request a response when you use it.

$http. Get ("). Then (function (response) {
  var time = response.config.responseTime- Response.config.requestTimestamp;
  Console.log (' The time required for the request is ' + times ');
}
 



Request error recovery, request interception

Simulate a request to intercept an error condition:

App.factory (' Requestrejector ', [' $q ', function ($q) {
  var requestrejector = {
    request:function (config) { Return
      $q. Reject (' requestrejector ');
    }
  ;
  return requestrejector;
}])

Intercept Request Error:

App.factory (' Requestrecoverer ', [' $q ', function ($q) {
  var requestrecoverer = {
    Requesterror:function ( Rejectreason) {
      if (Rejectreason = = ' Requestrejector ') {
        //restore request return
        {
          transformrequest:[],
          Transformresponse:[], method: ' Get
          ',
          url: ',
          headers:{
            Accept: ' Application/json, Text/plain, * *'
          }
        };
      } else {return
        $q. Reject (Rejectreason);}}
  ;
  
  return requestrecoverer;
}])

Register Interceptor:

App.config ([' $httpProvider ', function ($httpProvider) {
  $httpProvider. Interceptors.push (' Requestrejector ');
  $httpProvider. Interceptors.push (' Requestrecoverer ');
}]
 

Session error recovery, responding to interception

App.factory (' Sessionrecoverer ', [' $q ', ' $injector ', function ($q, $injector) {
 var sessionrecoverer = {
  Responseerror:function (response) {
   //If session expires if
   (Response.Status = = 419) {
    var sessionservice = $ Injector.get (' Sessionservice ');
    var $http = $injector. Get (' $http ');
    var deferred = $q. Defer ();
    
    Create a new session
    Sessionservice.login (). Then (Deferred.resolve, deferred.reject);
    
    Return Deferred.promise.then (function () {
     reutrn $http (response.config);
    })
   }
   Return $q. Reject (response);
  }
 ;
 
 return sessionrecoverer;
}])

The above is the entire content of this article, I hope to help you learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.