1

在我的Angularjs应用程序中,我有一个工厂,需要对用户进行身份验证。我正在使用httpProvider来设置默认值。但是我收到错误,说明$httpProvider未定义。无法在angularjs工厂内设置http默认值

'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'; 

我然后在工厂的依赖

'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

请让我知道我错了加入$httpProvider尝试。

回答

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; 
}]); 
+0

我在你的代码片段中看到了这个:'$ httpProvider.interceptors.push('authInterceptorService');'如果我有很多服务需要使用'拦截器'? – zilcuanu

+0

有一个问题。我在哪里配置定义?我将'config'设置为'undefined' – zilcuanu

+0

@Pradeep,你正在问的是哪个'config'? 'angular.module.config()'或名称为“config”的参数? –

2

$ httpProvider仅在配置像

angular.module('myApp') 
.config(function($httpProvider){ 
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'; 
}) 
+0

将这个配置被应用在整个应用程序的所有请求,或者我们需要使用'interceptors'所有'request'? – zilcuanu

+0

@Pradeep是的,它将适用于所有请求:) – Rebornix