Http interception in AngularJS and angularjs Interception

Source: Internet
Author: User

Http interception in AngularJS and angularjs Interception

Http InterceptionThat is, $ http service allows us to interact with the server. Sometimes we want to do something before sending a request and after receiving a response.
$ HttpProvider contains an array of interceptors.

Create an interceptor.

app.factory('myInterceptor', ['$log', function($log){  $log.debug('');    var myInterceptor = {};    return myInterceptor;}])

Register interceptor.

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

The following are some examples of $ http interception.

■ Asynchronous operations in the interceptor

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;})

The above is a Request Interception. An asynchronous operation is performed to update the config according to the asynchronous operation results.

Of course, response interception is also available.

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 interception and Request Interception

The server has two types of authentication: cookie-based and token-based. For token-based verification, when a user logs on, the user obtains a token from the server, which is sent to the server at each request.

Create an injector for 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;}])

The token returned from the server is placed in config. headers.

Register injector:

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

Send a request:

$http.get('');

The interception is roughly as follows:

{  "transformRequest":[null],  "transformResponse":[null],  "method":"GET",  "url":"",  "headers":{    "Accept": "application/json, text/plain,*/*"  }}

After the interception, 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;}])

The above code intercepts requests and responses and assigns the current time to config. requestTimestamp and config. responseTimestamp.

Register the Interceptor:

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

Then, the time consumed by the request response can be calculated.

$ Http. get (''). then (function (response) {var time = response. config. responseTime-response. config. requestTimestamp; console. log ('request elapsed time' + time );})

■ Request error recovery and Request Interception

Simulate a Request Interception error:

app.factory('requestRejector',['$q', function($q){  var requestRejector = {    request: function(config){      return $q.reject('requestRejector');    }  };  return requestRejector;}])

Request Interception error:

App. factory ('requestrecoverer', ['$ Q', function ($ q) {var requestRecoverer = {requestError: function (rejectReason) {if (rejectReason = 'requestreobjector ') {// restore request return {transformRequest: [], transformResponse: [], method: 'get', url: '', headers: {Accept: 'application/json, text/plain, */* '}};} else {return $ q. reject (rejectReason) ;}}; return requestRecoverer ;}])

Register the Interceptor:

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

■ Session error recovery, response Interception

App. factory ('sessionrecoverer', ['$ Q',' $ injector ', function ($ q, $ injector) {var sessionRecoverer = {responseError: function (response) {// if the 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 all the content of this article, hoping to help you learn.

Articles you may be interested in:
  • Comparison and analysis of the difference between $ http. post and jQuery. post in AngularJS
  • Analysis on AngularJs HTTP Response interceptor
  • Quick learning of AngularJs HTTP Response interceptor
  • In AngularJS, how does one use $ http to add, delete, modify, and query the data table of the Alibaba lab?
  • Details about $ http cache in AngularJS and how to process multiple $ http requests
  • Introduction to $ http service usage in AngularJS

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.