AngularJS-配置$httpProvider的未知提供程序
在以下代码示例中:AngularJS-配置$httpProvider的未知提供程序,http,angularjs,configuration,provider,Http,Angularjs,Configuration,Provider,在以下代码示例中: myApp.config(['$httpProvider', function($httpProvider, $cookieStore) { $httpProvider.defaults.withCredentials = true; $httpProvider.defaults.headers.get['Authorization'] = 'Basic '+ $cookieStore.get('myToken'); return JSON.st
myApp.config(['$httpProvider', function($httpProvider, $cookieStore) {
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.headers.get['Authorization'] = 'Basic '+ $cookieStore.get('myToken');
return JSON.stringify(data);
}]);
我得到一个angularjs错误,比如“未知提供者$cookieStore”
“myApp”有dependenciy和“ngCookies”,angular-cookies.min.js已经过时,那么代码有什么问题
这就是我在.config中执行此操作的事实吗?您可能需要添加cookieStore
myApp.config(['$httpProvider', '$cookieStore', function($httpProvider, $cookieStore)
因为只有在配置时才能传递提供程序,所以我最终完成了http参数的覆盖,不是使用请求转换器,而是通过创建一个服务作为工厂来执行请求 以下是服务的代码示例(未测试,仅供参考): 用法示例(未测试,仅供参考):
使用Module.run()似乎是设置始终需要的标题的更干净的方法。请看我的答案:我遇到了同样的问题,所以我将发布我是如何解决这个问题的。我基本上使用$injector模块手动获取我所需的服务实例。注意,这也适用于用户定义的服务
angular.module('app').
config(config);
config.$inject = ['$httpProvider'];
function config($httpProvider) {
//Inject using the $injector
$httpProvider.interceptors.push(['$injector', function($injector){
return {
request: function(config) {
//Get access by injecting an instance of the desired module/service
let $cookieStore = $injector.get('$cookieStore');
let token = $cookieStore.get('your-cookie-name');
if (token) {
config.headers['x-access-token'] = token;
}
return config;
}
}
}])
}
你为什么不给我们看一下你的
myApp
初始化代码。已经测试过了,错误已经消除了,但是我得到了一个“不可能做的未定义”,即$cookieStore是未定义的。这是真的。在配置部分,您只能使用提供程序,而在.run部分,您只能使用实例。我猜cookieStore不是一个供应商该死的。在使用$http进行请求时,是否有其他方法可以动态设置头?我认为您可以转换请求和响应头。不过我自己还没试过。选中Yep中的“transforming”,事实上该代码已经被放入一个转换器中,配置到$httpProvider上。但最后,由于一起发现的原因,我通过创建一个带有“publicRequest”和“privateRequest”方法的服务“RequestService”,来使用$http并自动将我的令牌参数添加到$http,从而解决了这个问题。我将用回答和代码示例更新我的问题。感谢您的帮助这也有问题,因为来自工厂的标题将是静态的。尝试登录,然后退出,然后再次登录,您会发现它仍在使用旧令牌。
angular.module('sharewebapp', ['myapp-http-request'])
.controller('MyController', ['MyRequests', function(MyRequests){
MyRequests.authentifiedRequest('DELETE', '/logout', '', function(){alert('logged-out');}, function(){alert('error');})
}]);
angular.module('app').
config(config);
config.$inject = ['$httpProvider'];
function config($httpProvider) {
//Inject using the $injector
$httpProvider.interceptors.push(['$injector', function($injector){
return {
request: function(config) {
//Get access by injecting an instance of the desired module/service
let $cookieStore = $injector.get('$cookieStore');
let token = $cookieStore.get('your-cookie-name');
if (token) {
config.headers['x-access-token'] = token;
}
return config;
}
}
}])
}