AngularJS Interceptors and great examples

Source: Internet
Author: User

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:

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

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

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

Interceptors allow you to:

    • intercepts the request by implementing the request method: The method executes before the $http sends the request channel background, 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.

    • intercepts the response by implementing the response method: The method executes after the $http receives 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.

    • intercept request exceptions by implementing the Requesterror 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.

    • block The response exception by implementing the Responseerror method: Sometimes we fail the background call. 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.

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

Module.factory (' Myinterceptor ', [' $q ', ' Someasyncservice ', function ($q, someasyncservice) {    var Responseinterceptor = {        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 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):

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:

$http. Get (' Https://api.github.com/users/naorye/repos ');

The sessionInjector configuration object before being intercepted is this:

{    "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:

{    "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.

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:

$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 .

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 (rejectr Eason) {if (Rejectreason = = = ' Requestrejector ') {//Recover the request return                    {transformrequest: [], Transformresponse: [], Method: ' GET ', URL: ' Https://api.github.com/users/naorye/repos ', headers: {ACC            EPT: ' 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.

$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.

Module.factory (' Sessionrecoverer ', [' $q ', ' $injector ', function ($q, $injector) {var sessionrecoverer = {Respon  Seerror:function (response) {//Session has expired if (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 login method, logs the user in using the Curren T credentials and//returns a Promise Sessionservice.login () then (Deferred.resolve, Deferre                D.reject); When the session is recovered, make the same backend call again and chain the request return Deferred.promi                Se.then (function () {return $http (response.config);            });        } return $q. Reject (response);    }    }; return sessionrecoverer;}]); Module.config ([' $Httpprovider ', function ($httpProvider) {$httpProvider. Interceptors.push (' Sessionrecoverer ');}]); 

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)

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.