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