Implementation of http Interceptor Interceptors in angular

  • 2021-07-22 08:56:55
  • OfStack

In the angularJs, an api-interceptors is added to process the global http request system 1

Interceptors has two processing opportunities, namely:

Other program code processes HTTP requests after they are executed and before they are actually issued from the browser After receiving the response to the request, the response to the request is processed before being handed over to other program code for processing

Its reference scenarios include

Global processing error System 1 performs authentication class 1 processing Preprocess all outgoing requests Preprocess all received responses and so on

Examples of use are as follows:


commonService.config(['$httpProvider',function($httpProvider){

    //$httpProvider.defaults.headers.common = {'X-Auth-Token': $.cookie('x_auth_token'),'Content-Type':'application/json;charset=UTF-8'};

    // Add interceptors; 

    $httpProvider.interceptors.push(function ($q) {

      return {

        request: function (obj) {
               

          $('.loading').show();

          obj.headers['X-Auth-Token'] = $.cookie('x_auth_token');

          if(!obj.headers['Content-Type'])

            obj.headers['Content-Type'] = 'application/json;charset=UTF-8';

 

          var url, params,method;

       

          // Franchisee request 

          mylog('jiamengdian::',sessionStorage.getItem("chainStorefrnId"));

          if(sessionStorage.getItem("chainStorefrnId")){

            // Add operators id , name And storeid Such information 

            // Name of operator 

            var operatorName = $.cookie("userType") == "employee" ? decodeURI($.cookie("username")) : decodeURI($.cookie("frnName"));

            // Operator id

            var operatorId = $.cookie("userId");

            // Franchise store id

            var operatorStoreId = $.cookie("frnId");

            if (obj.method) {

              method = obj.method.toLowerCase();

            } else {

              method = "get";

            }

            // Deal with url Distinguish between initial credit granting and additional credit granting 

            var flag_url = sessionStorage.getItem('chainStoreFlag');

            mylog('flag_url',flag_url);

            if(flag_url && flag_url == "firstcredit"){

 

              // Submission requires adding the franchise store logo 

              if(obj.url.indexOf("firstcredit/createPerFirstCredit")!=-1){

                // Identify individual submissions 

                obj.url = obj.url.replace('firstcredit/createPerFirstCredit','firstcredit/perFirstCreditByFranchisee');

              }

              else if(obj.url.indexOf("firstcredit/createBusiFirstCredit")!=-1){

                // Identify enterprise submission 

                obj.url = obj.url.replace('firstcredit/createBusiFirstCredit','firstcredit/createBusiFirstCreditByFranchisee');

              }

             
              } else {

                url = obj.url + "?creditType=1&operatorName=" + operatorName + "&operatorId=" + operatorId + "&operatorStoreId=" + operatorStoreId;

               }

            }

          return obj;

        },

        response: function (res) {

          $(".loading").hide();

          return res;

        },

        responseError: function (err) {

          $(".loading").hide();

          return $q.reject(err);

        }

      };

    });

  }]); 

There are four methods to change api, namely request, requestError, response and responseError. These four methods are not required and can be called according to needs. The first two are the pre-processing of requests, and the last two are the processing of responses to requests.

request: Receive 1 parameter, which is the standard config object in $http, and also need to return 1 standard config. At this time, you can add all kinds of authentication information, and you can also start the progress bar here requestError: When there are more than one Interceptor, requestError will be executed when the first Interceptor throws an error or executes $q. reject (), and the received parameters will correspond to the error response: Accept one request object parameter, and return directly without processing. At this time, you can also display the progress bar as successfully completed. Of course, if the status code of HTTP is still 200 when the back-end API returns a custom error, you can handle the custom error here. You can also do some processing on the returned data, and pay attention to setting the progress bar as completed responseError: This is the key point, that is, it can handle standard Http errors, such as 5021, which often occurs in CGI such as PHP when the server does not respond, and can also handle various custom errors with HTTP status code not 200

Related articles: