我在每个请求之前有一个包装器问题(添加一个值为X-CSRF-TOKEN的标头)和响应(获取一个新的X-CSRF-TOKEN标记)
但我遇到了一个错误:
Error: $ injector: unpr
Unknown Provider
Unknown provider: $ httpProviderProvider <- $ httpProvider <- HttpPreConfigController <- LoginService
授权模块:
var appAuth = angular.module("app-auth", ["ngResource", "ngRoute", "ngCookies"]);
控制器:
appAuth.controller("LoginController", function ($scope, $timeout, $window, $rootScope, LoginService) {
$scope.login = function () {
LoginService.getUser().then(function (response) {
...
});
};
});
服务:
appAuth.factory("LoginService", function ($resource, $route, $cookieStore, $q, $rootScope, HttpPreConfigController) {
var LoginService;
LoginService = {
getUser: function () {
return HttpPreConfigController.get('/rest/user');
}
};
return LoginService;
});
和包装器:
appAuth.factory('HttpPreConfigController', ['$injector', '$cookieStore', '$httpProvider', function ($injector, $cookieStore, $httpProvider) {
var $http = $injector.get('$http');
$http.defaults.transformRequest.push(function (data, headers) {
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRF-TOKEN';
$httpProvider.defaults.headers.common['X-CSRF-TOKEN'] = $cookieStore.get('X-CSRF-TOKEN');
});
$http.defaults.transformResponse.push(function (data, headers) {
$cookieStore.put("X-CSRF-TOKEN", headers('X-CSRF-TOKEN'));
});
return $http;
}]);
你能摆脱这个错误吗?
答案 0 :(得分:1)
您收到此错误,因为提供商只能注入应用的配置阶段。因此,您应该将代码从factory
移动到config
块,以实现此目的。希望这会有所帮助。