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).