12

在以下代码示例中:

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 是laoded,那么该代码有什么问题?

这是我在 .config 中这样做的事实吗?

4

4 回答 4

15

因为只能在配置时传递提供程序,所以我终于完成了对我的 http 参数的覆盖,而不是使用请求转换器,而是通过创建一个服务作为工厂来执行请求。

这是服务的代码示例(未经测试,仅供参考):

angular.module('myapp-http-request', []);
angular.module('myapp-http-request')
.factory('MyRequests', function($http, $cookieStore){

    return {
        request: function(method, url, data, okCallback, koCallback){
            $http({
                method: method,
                url: url,
                data: data
            }).success(okCallback).error(koCallback);
        },
        authentifiedRequest: function(method, url, data, okCallback, koCallback){
            $http({
                method: method,
                url: url,
                data: data,
                headers: {'Authorization': $cookieStore.get('token')}
            }).success(okCallback).error(koCallback);
        }
    }
});

以及使用示例(未经测试,仅供参考):

angular.module('sharewebapp', ['myapp-http-request'])
.controller('MyController', ['MyRequests', function(MyRequests){
    MyRequests.authentifiedRequest('DELETE', '/logout', '', function(){alert('logged-out');}, function(){alert('error');})
}]);
于 2013-06-26T10:43:47.853 回答
2

您可能需要添加 cookieStore

myApp.config(['$httpProvider', '$cookieStore', function($httpProvider, $cookieStore) 
于 2013-06-26T09:19:04.710 回答
2

我遇到了同样的问题,所以我会发布我是如何解决它的。我基本上使用 $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;
    }
  }
}])
}
于 2016-09-09T04:08:57.757 回答
0

使用 Module.run() 似乎是设置始终需要的标头的一种更简洁的方法。在这里查看我的答案:AngularJS pass requestVerificationToken to a service

于 2014-01-13T15:11:37.293 回答