Analysis of Angularjs HTTP response Interceptor _angularjs

Source: Internet
Author: User
Tags error handling

Why do you use interceptors?

At any time, if we want to add global functionality to a request, such as identity authentication, error handling, etc., it is a good way to implement a request before it is sent to the server or when the server returns.

ANGULARJS provides a way to deal with the global dimension through interceptors.

Interceptors allow you to:

Blocking requests by implementing the request method: This method executes before the $http sends a request path, so you can modify the configuration or do something else. The method receives the request configuration object (requests configuration object) as an argument and must then return the configuration object or promise. If an invalid configuration object or promise is returned, it is rejected, causing the $http call to fail.

Intercepts the response by implementing the Response method: This method executes after the $http receives a response from the background, so you can modify the response or do something else. The method receives the Response object (response object) as an argument, and then must return the response object or promise. The response object includes the request configuration (requests configuration), header (headers), status, and data from the background. If an invalid response object is returned or the promise is rejected, the $http call fails.

Block request exceptions by implementing the Requesterror method: Sometimes a request fails or is rejected by the interceptor. Requesting an exception interceptor captures requests that have been interrupted by the last request interceptor. It can be used to recover requests or sometimes to undo the configuration that was made prior to the request, such as closing the progress bar, activating the button and the input box, and so on.

Blocking response exceptions by implementing the Responseerror method: sometimes our backend calls fail. It is also possible that it was rejected by a request interceptor or interrupted by the last response interceptor. In this case, the response exception interceptor can help us recover the background call.

The core of the interceptor is the service factory, by adding a service factory to the $httpprovider.interceptors array. Register in the $httpprovider.

ANGULARJS provides four types of interceptors, two of which are successful interceptors (request, response), and two failure interceptors (Requesterror, Responseerror).

to add one or more interceptors to a service:

Angular.module ("myApp", []) 
  . Factory (' Httpinterceptor ', [' $q ', ' $injector ', function ($q, $injector) { 
    var Httpinterceptor = { 
      ' Responseerror ': function (response) { 
        ... 
        Return $q. Reject (response); 
      }, 
      ' response ': function (response) { 
        ... 
        return response; 
      }, 
      ' request ': function (config) { 
        ... 
        return config; 
      }, 
      ' Requesterror ': function (config) { 
        ... 
        Return $q. Reject (config); 
      } 
  return httpinterceptor; 

Then use $httpprovider to register the interceptor in the. config () function

Angular.module ("myApp", []) 
. config ([' $httpProvider ', function ($httpProvider) { 
  $ HttpProvider.interceptors.push (' Httpinterceptor '); 

Actual example: (Interception of 401, 404)

Routerapp.config ([' $httpProvider ', function ($httpProvider) { 
    $httpProvider. Interceptors.push (' Httpinterceptor '); 
  } ]); 
  Routerapp.factory (' Httpinterceptor ', [' $q ', ' $injector ', function ($q, $injector) { 
    var httpinterceptor = 
      ' Responseerror ': function (response) { 
        if (Response.Status = = 401) { 
          var rootscope = $injector. Get (' $rootScope '); 
          var state = $injector. Get (' $rootScope '). $state. Current.name; 
          Rootscope.statebeforlogin = State; 
          Rootscope. $state. Go ("login"); 
          Return $q. Reject (response); 
        else if (response.status = = 404) { 
          alert ("404!"); 
          Return $q. Reject (response);}} 
      , 
      ' response ': function (response) {return 
        response; 
      } 
    } return 
    httpinterceptor; 
  }  

Session injection (Request interceptor)

Here are two ways to implement server-side authentication. The first is the traditional cookie-based validation. Each requested user is authenticated by a service-side cookie. Another way is token-based validation. When a user logs in, he gets a sessiontoken from the background. Sessiontoken identifies each user on the server side and is included in each request sent to the server.

The following sessioninjector adds a X-session-token header for each captured request (if the current user is logged in):

<!--lang:js-->
module.factory (' Sessioninjector ', [' Sessionservice ', function (sessionservice) {
  var Sessioninjector = {
    request:function (config) {
      if (!) Sessionservice.isanonymus) {
        config.headers[' x-session-token '] = Sessionservice.token;
      }
      return config;
    }
  ;
  Return Sessioninjector
}]);
Module.config ([' $httpProvider ', function ($httpProvider) {
  $httpProvider. Interceptors.push (' Sessioninjector ') );
}]);

Then create a request:

<!--lang:js-->
$http. Get (' Https://api.github.com/users/naorye/repos ');

The configuration object before being intercepted by Sessioninjector is this:

<!--lang:js-->
{
  "transformrequest": [
    null
  ],
  "Transformresponse": [
    null
  ],
  ' method ': ' Get ',
  ' url ': ' Https://api.github.com/users/naorye/repos ',
  ' headers ': {
    ' Accept ': ' Application/json, Text/plain, */* "
  }
}

The configuration object after being intercepted by Sessioninjector is this:

<!--lang:js-->
{
  "transformrequest": [
    null
  ],
  "Transformresponse": [
    NULL
  ],
  ' method ': ' Get ',
  ' url ': ' Https://api.github.com/users/naorye/repos ',
  ' headers ': {
    ' Accept ":" Application/json, Text/plain, */* ",
    " X-session-token ": 415954427904
  }
}

The above content has introduced the Angularjs HTTP response interceptor The related knowledge, hoped this article sharing can bring the help to everybody.

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.