在我的Angularjs应用程序中,我有一个工厂,我需要对用户进行身份验证。我使用httpProvider
来设置默认值。但我收到的错误是$httpProvider
未定义。
'use strict';
angular.module('myApp')
.factory('authService', function ($q, $http, $rootScope, $window) {
return {
authenticateUser: function () {
........
........
$httpProvider.defaults.headers.common['Accept'] = 'application/json, text/javascript';
$httpProvider.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8';
然后我尝试在工厂依赖项中添加$httpProvider
'use strict';
angular.module('myApp')
.factory('authService', function ($q, $http, $rootScope, $window, httpProvider ) {
return {
authenticateUser: function () {
........
........
$httpProvider.defaults.headers.common['Accept'] = 'application/json, text/javascript';
$httpProvider.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8';
这次我得到了Unknown provider: $httpProviderProvider <- $httpProvider <- authService
请让我知道我哪里出错。
答案 0 :(得分:2)
$ httpProvider只能在配置
中访问angular.module('myApp')
.config(function($httpProvider){
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
})
答案 1 :(得分:2)
您无法在工厂内获得服务提供商。
您可以使用interceptors
为每个http请求添加默认值。
angular.module('myApp').config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptorService');
});
angular.module('myApp').factory('authInterceptorService', ['$q', '$location', 'localStorageService', function ($q, $location, localStorageService) {
var authInterceptorServiceFactory = {};
var _authentication = {
isAuth: false,
userName: ""
};
var _request = function (config) {
config.headers = config.headers || {};
var authData = localStorageService.get('data');
if (authData) {
config.headers.Authorization = 'Bearer ' + authData;
}
return config;
}
authInterceptorServiceFactory.request = _request;
return authInterceptorServiceFactory;
}]);