javascript - 从 ngInit 在 AngularJS 中全局设置自定义 HTTP header

标签 javascript http rest angularjs basic-authentication

我无法在 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]

我尝试在configrun、 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/

相关文章:

javascript - 将鼠标悬停在数据表中的图标上时显示弹出窗口

javascript - 如何 react 性地渲染你自己的对象实例? (不是游标对象)

javascript - 如何使用 XS 从 HANA 数据库返回多行?

http - Spring RestTemplate - 带请求正文的 http GET

Spring mvc Controller 处理所有请求,不应该那样做

javascript - 点击卡片后响应来自外部 API 的获取请求

rest - RESTful API 的 SSL 有多贵?

c# - 将模型编写为 Javascript 中可用的对象

javascript - 使用 AngularJS 将 JSON 数据保存到服务器 - 在页面刷新时消失

python - 有没有办法从资源中获取flask_restful中的完整url