Describes how to add an interceptor to the $ http service built in Angular. js and how to add an interceptor to angular. js.

Source: Internet
Author: User

Describes how to add an interceptor to the $ http service built in Angular. js and how to add an interceptor to angular. js.

Preface

In the Angular framework, the creation team encapsulates Ajax requests for users and exposes related interfaces through the $ http service. angular pointed out in its official documentation that the $ http service underlying layer has made corresponding countermeasures against common Web security attacks, that is to say, Ajax encapsulated by $ http service provides users with more security protection. as a framework, it is necessary to ensure the availability and adaptability of the framework. angular also shows such a good style in design and implementation. when using Ajax, we sometimes want to handle the request before it is initiated or after it is received. For example, before a request is initiated, add the packet segment to the request header. manage the processing status of a request when the request is returned, such as processing the 404 status in a unified manner. angular's $ http service fully considers the above situation during design and implementation. next, let's take a look at how to add an interceptor to the $ http service and how to implement similar Interceptor Mechanisms in our own services.

What is an interceptor-What are Interceptors?

Interceptor is a common mechanism in the server framework, such as spring and Struts2. the interceptor provides a mechanism for developers to define the code executed before and after an action. The code can be the code that is blocked before an action is executed, it can also be code for modifying certain behaviors of the target action. (In AOP (Aspect-Oriented Programming), the interceptor is used to intercept a method or field before it is accessed, and then add some operations before or after it. Common in Spring frameworks)

$ Http interceptor

View the API or source code. We can find that Angular provides an array named interceptors through httpProvider. this array accepts the interceptor service registration. The interceptor chain will be formed through the registration of process times. in this way, angular will modify the corresponding Ajax action by defining the interception point (aspect. I will not talk about the theory much. Next I will start to practice:

How to declare an interceptor in Angular

// Interceptor declarationmodule.factory('httpInterceptor', ['$log', function($log) {  $log.debug('$log is here to show you that this is a regular factory with injection');  return {       // do something      };}]);

How to register the declared Interceptor to the $ http service

// Add the interceptor to $httpProvider.interceptorsmodule.config(['$httpProvider', function($httpProvider) {   $httpProvider.interceptors.push('httpInterceptor');}]);

Through the two simple steps above, we have basically completed writing and adding http service interceptors. however, the above code snippets are not actually usable. To implement interception operations, we also need to follow the points exposed by the http service that can be intercepted for relevant code writing.

$ What points does httpProvider expose to intercept?

  1. Request: The request method can be used to intercept requests. This method will be executed before the http sends the request to the server. Therefore, we can modify the configuration or perform other operations in the line of sight of this method. This method receives the request configuration object (requestconfigurationobject) as the parameter, and then must return the configuration object or promise. If an invalid configuration object or promise is returned, the request is rejected, resulting in an http call failure.
  2. The response: response method can intercept the response. This method will be executed after the http receives the response from the server. Therefore, we can modify the response message or perform other operations. This method receives the response object as a parameter, and then must return the response object or promise. Response objects include requestconfiguration, headers, status, and data from the background ). If an invalid response object or promise is returned, the http call fails.
  3. RequestError: The requestError method can intercept request exceptions: Sometimes a request fails to be sent or is rejected by the interceptor. The request exception interceptor captures the requests interrupted by the previous request interceptor. It can be used to restore a request or sometimes to cancel the configuration made before the request, such as closing the progress bar, activating the button, and entering the box.
  4. ResponseError: The responseError method can intercept response exceptions: Sometimes our background call fails. It may also be rejected by a request interceptor or interrupted by the previous response interceptor. In this case, the response to the exception interceptor can help us recover background calls.

The interface exposed above is also very simple to use. We can declare a $ http service interceptor like a simple service, the configured interceptor is used by angular Injection mechanism.

// Declare an interceptor module just like declaring an Angular service. factory ('sessioninjector ', ['authservice', function (authService) {return {request: function (config) {if (! AuthService. isAnonymus) {config. headers ['x-session-token'] = authService. token;} return config ;};}]); // Add the interceptor we declare to the $ httpProvider interceptor chain, angular Injection will help us improve the module. config (['$ httpProvider', function ($ httpProvider) {$ httpProvider. interceptors. push ('sessioninjector');}]);

$ Asynchronous support for http service interceptor

In some scenarios, we hope to execute some asynchronous operations in the interceptor. then different interception operations are performed based on different processing results. AngularJS also supports this feature well during design. angularJS allows us to return a promise object in the interception method. for example, in the http service, if we return a promise object, the http service will delay initiating a network request or responding to the request results.

module.factory('myInterceptor', ['$q', 'someAsyncService', function($q, someAsyncService) {  var requestInterceptor = {    request: function(config) {      var deferred = $q.defer();      someAsyncService.doAsyncOperation().then(function() {        // Asynchronous operation succeeded, modify config accordingly        ...        deferred.resolve(config);      }, function() {        // Asynchronous operation failed, modify config accordingly        ...        deferred.resolve(config);      });      return deferred.promise;    },    response: function(response) {          var deferred = $q.defer();          someAsyncService.doAsyncOperation().then(function() {            // Asynchronous operation succeeded, modify response accordingly            ...            deferred.resolve(response);          }, function() {            // Asynchronous operation failed, modify response accordingly            ...            deferred.resolve(response);          });          return deferred.promise;        }  };  return requestInterceptor;}]);

In the above example, when a request is initiated, if the corresponding deferred is rejected, the http request will fail (if the packet capture analysis is performed, you will find that the http request has not been initiated ). when the request is responded, if the deferred is rejected, the request will also fail. (packet capture analysis, network requests are returned ).

Summary

The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.

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.