我无法在 AngularJS 中设置取自 ngInit
的自定义 HTTP header 。
我在 html 中使用 ngInit 设置变量:
<div ng-init="myApiKey='valueOfVar'"></div>
现在我想在所有 HTTP 请求中使用这个变量。我也尝试在 app.config 和 Controller 中设置它。
如果我立即设置它,变量是未定义的。
如果我在
$scope.$watch
回调函数中设置它,变量是 已定义,但 HTTP 请求没有该 header 。
我设置标题:
$http.defaults.headers.common.Authorization = 'something';
(或通过 $httpProvider
,当在 app.config 中时),然后在利用 $resource
的服务中使用它。我的代码看起来像 [this][1]
我尝试在config
、run
、 Controller 和服务中设置它,但对我来说还没有任何效果。预先感谢您提供的任何建议。
编辑: 现在我有了拦截器:
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;
}
};
}]);
但是$rootscope.apiKey
(在主 Controller 中设置)在第一次调用时是undefined
。之后,就可以了(并设置)。
最佳答案
以下代码将允许您拦截应用程序的所有 http 请求 并在请求的 header 中添加属性“语言”
angular.module('app', ['ngRoute', 'ngResource']).run(function($http) {
$http.defaults.headers.common.language='fr-FR';
});
我们可以在http header中添加很多属性
关于javascript - 从 ngInit 在 AngularJS 中全局设置自定义 HTTP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20102605/