Pass a common data in all $http services in angularjs

43 Views Asked by At

I wish to send a particular data in all the $http calls. Can i define it somewhere so that i need not alter all the $http calls. For example,

  $http({
      method: 'POST',
      url: serviceUrl,
      data: {
          "key1": data1,
          "key2": data2,
      }
  })

Add a data3 as default in all my $http calls. Thanks in advance for your response.

1

There are 1 best solutions below

2
Kinglish On BEST ANSWER

You can transform or intercept the $http object with $httpProvider

var app = angular.module('test', []);
app.config(function ($httpProvider) {
    $httpProvider.defaults.transformRequest = function(data){
        if (data === undefined) {
            return data;
        } 
        data.key3 = "This will always be set in a POST";

        return $.param(data);
    }
});

I've never tried to append the POST data like this, but it should work.

For GET params transforming...

$httpProvider.interceptors.push(function() {
  return {
   'request': function(config) {
       //config.params contains query/request parameters
       if (config.params){
         config.params.key3 = "Hello World"
       }
       return config;
    }
  };
});