AngularJS Interceptors and great examples

Source: Internet
Author: User

Catalogue [-]

    • What is an interceptor?
    • Asynchronous operation
    • Example
    • Session Injection (Request blocker)
    • Timestamp (Request and response interceptors)
    • Request recovery (Request exception interception)
    • Session Recovery (response to exception blocker)
    • Summarize

Interceptors in AngularJS and useful Examples

There are dates, I like.

$httpAngularJS $http Service allows us to communicate with the background by sending HTTP requests. In some cases, we want to be able to capture all requests and operate before sending them to the server. In other cases, we want to capture the response and process it before the completion call is complete. A good example is handling global HTTP exceptions. Interceptors (interceptors) emerged. This article will introduce AngularJS interceptors, and give a few useful examples.

What is an interceptor?

$httpProviderThere is an interceptors array, and the so-called interceptor is simply a generic service factory registered to the array. The following example shows you how to create an interceptor:

<!-- lang: js -->module.factory(‘myInterceptor‘, [‘$log‘, function($log) {    $log.debug(‘$log is here to show you that this is a regular factory with injection‘); var myInterceptor = { .... .... .... }; return myInterceptor;}]);

It is then added to the array by its name $httpProvider.interceptors :

<!-- lang: js -->module.config([‘$httpProvider‘, function($httpProvider) {    $httpProvider.interceptors.push(‘myInterceptor‘);}]);

Interceptors allow you to:

  • To request intercept a request by implementing A method: The method $http executes before the request is sent back to the backend, so you can modify the configuration or do other things. The method receives the request configuration object (requests config objects) as a parameter, and then must return the configuration object or promise . If an invalid configuration object is returned or promise is rejected, the $http call fails.

  • To response intercept a response by implementing a method: The method $http executes after receiving a response from the background, so you can modify the response or do other things. The method receives the Response object (response object) as a parameter, and then must return the response object or promise . The response object includes the request configuration, the header (headers), the State (status), and the data from the background. If an invalid response object is returned or promise is rejected, the $http call fails.

  • To requestError intercept a request exception by implementing a method: sometimes a request fails to send or is rejected by the interceptor. Request exception interceptors capture requests that were interrupted by a previous request interceptor. It can be used to restore the request or sometimes to undo the configuration that was made before the request, such as closing the progress bar, activating the button and the input box, and so on.

  • To responseError intercept a response exception by implementing the method: sometimes our back-end calls fail. It is also possible that it was rejected by a request interceptor or was interrupted by a response interceptor. In this case, the response exception blocker can help us to restore the background call.

    Asynchronous operation

Sometimes it is necessary to do some asynchronous operations in the interceptor. Fortunately, AngularJS allows us to return a promise deferred processing. It will delay sending the request in the request interceptor or defer the response in the response interceptor.

 <!--lang:js-->module.factory ( ' Myinterceptor ', [ ' $q ',  ' Someasyncservice ', function ($q, Someasyncservice) {var requestinterceptor = {request: function (config) {var deferr ed = $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;} }; return Requestinterceptor;}]);          

In this example, the request interceptor uses an asynchronous operation to update the configuration based on the results. It then resumes the operation with the updated configuration. If deferred rejected, the HTTP request fails.

In response to an interceptor example:

 <!--lang:js-->module.factory ( ' Myinterceptor ', [ ' $q ',  ' Someasyncservice ', function ($q, Someasyncservice) {var responseinterceptor = {response: function (response) {var de ferred = $q. Defer (); Someasyncservice.doasyncoperation () Then (function () {//asynchronous operation Succeeded, modify response accordingly function () {//asynchronous operation failed, modify response accordingly  ... Deferred.resolve (response); }); return deferred.promise;} }; return Responseinterceptor;}]);          

The deferred request is successful only if it is parsed, and if deferred rejected, the request will fail.

Example

In this section I will provide some examples of AngularJS interceptors to give you a better understanding of how they are used, and to show how they can help you. But keep in mind that the solution I offer here is not necessarily the best or the most accurate solution.

Session Injection (Request blocker)

There are two ways to achieve server-side authentication. The first is traditional Cookie-Based validation. Use cookies from the server to authenticate each requested user. Another way is to Token-Based verify. When a user logs in, he gets one from backstage sessionToken . sessionTokeneach user is identified on the server and is included in each request sent to the server.

The following sessionInjector adds a header for each captured request x-session-token (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 sessionInjector configuration object before being intercepted 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 sessionInjector configuration object after being intercepted 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 }}
Timestamp (Request and response interceptors)

Let's use interceptors to measure how long it takes to return a response from the background. You can add a timestamp to each request and response.

<!--Lang:js--Module.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 response;} }; return Timestampmarker;}]); module.config ([ ' $httpProvider ', function ($httpProvider) {$ HttpProvider.interceptors.push ( "Timestampmarker ');}]);      

And then we can do this:

<!-- lang: js -->$http.get(‘https://api.github.com/users/naorye/repos‘).then(function(response) {    var time = response.config.responseTimestamp - response.config.requestTimestamp; console.log(‘The request took ‘ + (time / 1000) + ‘ seconds.‘);});

Full code: Example for the Timestamp Marker

Request recovery (Request exception interception)

In order to demonstrate the request for exception interception, we need to simulate the previous interceptor rejecting the request for this situation. Our request for the exception blocker will get the reason for the rejection and the recovery request.

Let's create two interceptors: requestRejector and requestRecoverer .

<!--Lang:js-->module.factory (' Requestrejector ', [' $q ',function($Q) {var requestrejector = {request:function(config) {Return$q. Reject (' Requestrejector '); } };return requestrejector;}]); Module.factory (' Requestrecoverer ', [' $q ',function($Q) {var requestrecoverer = {requesterror:function(Rejectreason) {if (Rejectreason = = =' Requestrejector ') {Recover the requestreturn {transformrequest: [], Transformresponse: [], Method: ' GET ', url:  ' Https://api.github.com/users/naorye/repos ', Headers: {Accept:  ' Application/json, Text/plain, */* '}}; } else {return  $q. Reject ( Rejectreason); } } }; return Requestrecoverer;}]); Module.config ([ ' $httpProvider ',  function ( $httpProvider) { $httpProvider. Interceptors.push ( ' Requestrejector '); //removing ' requestrecoverer ' would result to failed request $ HttpProvider.interceptors.push ( "Requestrecoverer ');}]);      

Then, if you request as follows, we'll see it in log success , although requestRejector the request was rejected.

lang: js -->$http.get(‘https://api.github.com/users/naorye/repos‘).then(function() { console.log(‘success‘);}, function(rejectReason) { console.log(‘failure‘);});

Full code: Example for the Request Recover

Session Recovery (response to exception blocker)

Sometimes, in our single-page application, there is a loss of session. This situation may be due to a session expiration or server exception. Let's create an interceptor to restore the session and then automatically resend the original request (assuming the session expires).

For demonstration purposes, let's assume that a session has expired returning an HTTP status code of 419.

<!--Lang:js-->module.factory (' Sessionrecoverer ', [' $q ',' $injector ',function($q,$injector) {var sessionrecoverer = {responseerror:function(response) {Session has expiredif (Response.Status = =419) {var sessionservice =$injector. Get (' Sessionservice ');Var$http =$injector. Get (' $http ');var deferred =$q. Defer ();Create a new session (recover the session)We Use the login method, which logs the user in using the current credentials andReturns a Promise Sessionservice.login () then (Deferred.resolve, Deferred.reject); //when the session is recovered, make the same backend call again and chain the request return deferred.promise.then (function< Span class= "Hljs-params" > () {return  $http (response.config) ; }); } return  $q. Reject (response);}}; return Sessionrecoverer;}]); Module.config ([ ' $httpProvider ',  function ( $httpProvider) { $httpProvider. Interceptors.push (  

In this way, if the background call fails to cause the session to expire, sessionRecoverer a new session is created and then recalled back to the background.

Summarize

In this article I explained the knowledge about AngularJS interceptors, and I introduced, request response requestError and responseError interceptors, and explained how/when to use them. I also provide some useful examples of reality that you can use in your development.

I hope this article will make you feel good, just like I wrote it cool.
Good luck!
The second ye (Naorye)

from:http://my.oschina.net/ilivebox/blog/290881

AngularJS Interceptors and great examples

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.