title: Generating a unique value for a header on each $http call
body: <p>I have a fairly large AngularJS application and for logging purposes, I am being tasked with adding a custom header to all of our HTTP requests from the app that contain <strong>a unique ID for each request.</strong> This really is more valuable to our API calls, but as of now I'm just aiming for all requests (getting templates, styles, etc.)</p>
  
  <p>I am currently using a provider decorator to patch each of the methods exposed by <code>$HttpProvider</code> (implementation based on <a href="http://manikanta.com/blog/2013/07/25/decorate-angularjs-http-service-to-convert-put/" rel="nofollow">this post</a>), to attempt to call the ID method each time one of those <code>$http</code> methods runs, and add the appropriate header:</p>
  
  <pre><code>module.config([
    '$provide',
    function ($provide) {
      $provide.decorator('$http', [
        '$delegate',
        function addUniqueIdHeader($http) {
          var httpMethods = ['get', 'post', 'put', 'patch', 'delete'];
  
          /**
           * Patched HTTP factory function that adds a request ID each time it is called.
           * @param  {string} method - A valid HTTP method.
           * @return {function} A function that sets various request properties.
           */
          function httpWithHeader(method) {
            return function(url, data, config) {
              config = config || {};
              config.headers = config.headers || {};
  
              // the magic
              config.headers['My-Custom-Header'] = aUniqueId();
  
              data = data || {};
  
              config.method = method.toUpperCase();
  
              // return `$http` with a modified config, adding the URL and data passed in
              // `_.extend()` is lodash, not underscore.
              return $http(_.extend(config, {
                url: url,
                data: data
              }));
            }
          };
  
          // back up the orginal methods and patch
          _.each(httpMethods, function (httpMethod) {
            var backupMethod = '_' + httpMethod;
  
            $http[backupMethod] = $http[httpMethod];
            $http[httpMethod] = httpWithHeader(httpMethod);
          });
  
          return $http;
        }
      ]);
    }
  ]);
  </code></pre>
  
  <p>What I have so far works some of the time, but doesn't seem to work consistently (some API requests have it, some don't). I should note that we are using a quite old version of AngularJS (1.0.6) and no, I cannot upgrade (as much as I would love to) so the use of request interceptors is not possible. Additionally, we use Restangular for the majority of our API interactions.</p>
  
  <p>My question is, is using a provider decorator the right way to go? If so, is there a cleaner way to add the header without having to override/patch each individual HTTP method that I'm overlooking?</p>
  
  <p>Thanks in advance.</p>