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

Unable to set the http defaults inside the 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

请让我知道哪里出错了。

$httpProvider 只能在类似

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

您无法在工厂内获得服务提供商。

您可以使用 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;
}]);