title: Globally set custom HTTP header in AngularJS from ngInit
body: <p>I am unable to set custom HTTP header taken from <code>ngInit</code> in AngularJS.</p>
  
  <p>I set variable using ngInit in html:</p>
  
  <pre><code>&lt;div ng-init="myApiKey='valueOfVar'"&gt;&lt;/div&gt;
  </code></pre>
  
  <p>Now I want to use this variable in all HTTP requests. I tried to set it in app.config and in controller too.</p>
  
  <ul>
  <li><p>If I set it immediately, variable is undefined.</p></li>
  <li><p>If I set it in <code>$scope.$watch</code> callback function, variable is
  defined, but HTTP requests are without that header.</p></li>
  </ul>
  
  <p>I set header with:</p>
  
  <pre><code>$http.defaults.headers.common.Authorization = 'something';
  </code></pre>
  
  <p>(or via <code>$httpProvider</code>, when in app.config) and then use it in service utilizing <code>$resource</code>. My code looks like [this][1]</p>
  
  <p>I tried to set it in <code>config</code>, in <code>run</code>, in controller and as a service, but nothing worked for me yet. Thank you in advance for any advice given.</p>
  
  <p><strong>Edit:</strong>
  Now I have interceptor:</p>
  
  <pre><code>myApp.config(function ($httpProvider) {
      $httpProvider.interceptors.push('httpRequestInterceptor');
  });
  
  myApp.factory('httpRequestInterceptor', ['$rootScope', function($rootScope) {
      return {
          request: function($config) {
              $config.headers['Authorization'] = 'Basic ' + $rootScope.apiKey;
              return $config;
          }
      };
  }]);
  </code></pre>
  
  <p>But <code>$rootscope.apiKey</code> (which is set in main controller) is <code>undefined</code> at first call. After that, it's okay (and set).</p>