无法在angularjs工厂内设置http默认值

时间:2016-02-22 04:12:25

标签: angularjs angularjs-scope angularjs-service angularjs-factory

在我的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

请让我知道我哪里出错。

2 个答案:

答案 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;
}]);