Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  133] [ 1]  / answers: 1 / hits: 15538  / 11 Years ago, wed, november 20, 2013, 12:00:00

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


More From » http

 Answers
14

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.


[#74159] Tuesday, November 19, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
paolam

Total Points: 437
Total Questions: 107
Total Answers: 106

Location: Aland Islands
Member since Wed, Nov 17, 2021
3 Years ago
paolam questions
Thu, Oct 29, 20, 00:00, 4 Years ago
Wed, Nov 20, 19, 00:00, 5 Years ago
;