Globally set custom HTTP header in AngularJS from ngInit

15,454

Solution 1

OK, so for anybody trying to do the same - Interceptors were the key (thank you Fals a lot), but problem was with the $rootScope. As I wrote in question, when Interceptor was called the first time, $rootScope.apiKey wasn't set yet (on consecutive requests, it was already set).

Right way (or The working way) was to pass variable to AngularJS not through ngInit, but through $window. So I added to my HTML code:

<script>window.apiKey = 'myValue';</script>

and then pass it to Interceptor exactly the same way as $rootScope - You can literally just replace all occurences of $rootScope in edit of my question with $window and now it's working - even for the first request!

Thank you Fals once again.

Solution 2

the following code will allow you to intercept all http requestes of your application and to add a property 'language' in the header of the request

angular.module('app', ['ngRoute', 'ngResource']).run(function($http) {
  $http.defaults.headers.common.language='fr-FR';
});

we can add many properties in the http header

Solution 3

If you wanna modify request/response in AngularJS you should do a deeply read about Interceptor:

  • Angular JS Web Site: $http

You can call $http(config), where config is a object with every configuration. There's a configuration there for headers, where you should put your code:

headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent.

If you google about Interceptor, you will get a full list of blogs explaining how to use It, and providing example codes, here's one that help me out sometime ago:

Understanding angular $http interceptors

Share:
15,454
PhoenixS
Author by

PhoenixS

Updated on June 22, 2022

Comments

  • PhoenixS
    PhoenixS about 2 years

    I am unable to set custom HTTP header taken from ngInit in AngularJS.

    I set variable using ngInit in html:

    <div ng-init="myApiKey='valueOfVar'"></div>
    

    Now I want to use this variable in all HTTP requests. I tried to set it in app.config and in controller too.

    • If I set it immediately, variable is undefined.

    • If I set it in $scope.$watch callback function, variable is defined, but HTTP requests are without that header.

    I set header with:

    $http.defaults.headers.common.Authorization = 'something';
    

    (or via $httpProvider, when in app.config) and then use it in service utilizing $resource. My code looks like [this][1]

    I tried to set it in config, in run, in controller and as a service, but nothing worked for me yet. Thank you in advance for any advice given.

    Edit: Now I have interceptor:

    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;
            }
        };
    }]);
    

    But $rootscope.apiKey (which is set in main controller) is undefined at first call. After that, it's okay (and set).

    • Fals
      Fals over 10 years
      Why not set it in the server side?
    • PhoenixS
      PhoenixS over 10 years
      @Fals How? If I want to use that variable in Angular, then it has to be set in its js files, or not?
  • PhoenixS
    PhoenixS over 10 years
    Thank you. I'm almost there, but I can't get my $scope into interceptor, so I could take that variable from it (from the $scope). When I put it as an argument to request function (with $config - which works okay) it's undefined.
  • PhoenixS
    PhoenixS over 10 years
    OK - now I finally succeeded in injecting $rootScope in, my variable is set, but not for the first time, the interceptor is called. First HTTP request is without auth header, but others are okay. Don't you know, how to make it work even for the first time?