简体   繁体   中英

How to append some default data in $http before request sends

In my angular application I want to override $http. So whenever there is $http service call, it will append some default data in the original data and send the request. Similarly when a response comes it will check some specific data and reformat it and success() will get the modified response.

I am new to Angularjs. Can anyone help me on this?

Thank you in advance.

Take a look at $http interceptor ( https://docs.angularjs.org/api/ng/service/ $http). Using them, you can intercept the request and the response of the ajax request.

Create a service like:

module.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  return {
    'request': function(config) {
      // do something pre-request, like inject Headers properties:
      //config.headers['Authorization'] = '';
      return config;
    },

   'requestError': function(rejection) {
      //do something with the error
      return $q.reject(rejection);
    },


    'response': function(response) {
      // do something on success of request
      return response;
    },


   'responseError': function(rejection) {
      // do something on error like:
      //if(response.status == 401){
      //     userUnauthorized();
      //}
      return $q.reject(rejection);
    }
  };
});

In your app config, push the interceptor:

module.config(['$httpProvider', function($httpProvider) {  
    $httpProvider.interceptors.push('myInterceptor');
}]);

You have to explore through the $http method implemented in angular. You can see a function

function sendReq (config, reqData, reqHeaders)

Here you can change reqData as per your requirement. Now similarly inside success and done function you can use your code to manipulate the data before it is sent to the callback. Otherwise you can also change the data where it is coming from xhr request. This you will get from the function createxhr() written right there in angular

You can use the below code as well.

// alternatively, register the interceptor via an anonymous factory

$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
    return {
       'request': function(config) {
           // do your stuff
           return config;
        },

        'response': function(response) {
            // do your stuff
            return response;
        }
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM