Search code examples
angularjsangular-http-interceptors

Is it possible to add GET/POST parameters to Angular $http requests with an interceptor


Say I need to include a GroupId parameter to every request the user makes, but I don't want to modify every service call to include that. Is it possible to make that GroupId appended automatically to all requests, whether it is POST or GET query string?

I have been looking into the interceptor request function, but can't figure out how to make the change

** Edit **

Current working sample below is a combo of Morgan Delaney and haimlit's suggestions (I think it is a combom anyway). The basic idea is that if the request is a POST, modify config.data. For GET, modify params. Seems to work so far.

Still not clear on how the provider system works in Angular, so I am not sure if it is entirely approriate to modify the data.params properties here.

.config(['$httpProvider', function ($httpProvider) {
  $httpProvider.interceptors.push(['$rootScope', '$q', 'httpBuffer', function ($rootScope, $q, httpBuffer) {
      return {

          request: function (config) {

              if (config.data === undefined) {
                  //Do nothing if data is not originally supplied from the calling method
              }
              else {
                  config.data.GroupId = 7;
              }

              if (config.method === 'GET') {
                  if (config.params === undefined) {
                      config.params = {};
                  }
                  config.params.GroupId = 7;
                  console.log(config.params);
              }

              return config;
          }
      };
  } ]);
 } ]);

Solution

  • If your example works, great. But it seems to lack semantics IMHO.

    In my comments I mentioned creating a service but I've set up an example Plunker using a factory.

    Plunker

    Relevant code:

    angular.module( 'myApp', [] )
      .factory('myHttp', ['$http', function($http)
      {
        return function(method, url, args)
        {
          // This is where the magic happens: the default config
          var data = angular.extend({
            GroupId: 7
          }, args );
    
          // Return the $http promise as normal, as if we had just
          // called get or post
          return $http[ method ]( url, data );
        };
      }])
      .controller( 'myCtrl', function( $scope, $http, myHttp )
      {
        // We'll loop through config when we hear back from $http
        $scope.config = {};
    
        // Just for highlighting
        $scope.approved_keys = [ 'GroupId', 'newkey' ];
    
        // Call our custom factory
        myHttp( 'get', 'index.html', { newkey: 'arg' }).then(function( json )
        {
          $scope.config = json.config;
        });
      });