2013-05-07 17 views
5

我想做somtehing這樣的:角:混合供應商和定製服務模塊的config /運行

angular.module('app', []).config(
    [ '$httpProvider', 'customAuthService', 
    ($httpProvider, customAuthService) -> 
     $httpProvider.defaults.transformRequest.push (data) -> 
     if customAuthService.isLoggedIn 
      data['api_key'] = {token: @token} 
    ]) 

Angularjs doc,我不能這樣做在我moduleconfig塊,由於定製服務是不允許在那裏,我也不能做到這一點在run塊,因爲像$httpProvider提供商不準有:

Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.

Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

我該怎麼做才能增加我的一些配置依靠自制服務?

回答

7

總是可以得到一個注射器,然後回調函數(「服務定位器」的風格,而不是其在配置功能注入的依賴)內的服務的實例。

我想對特殊情況是可以的,雖然不是很漂亮的使用它廣泛。

.config([ '$httpProvider', function($httpProvider) { 
    $httpProvider.defaults.transformRequest.push(function(data) { 

     var $injector = angular.injector(['app']); 
     var customAuthService = $injector.get('customAuthService'); 

     // ... 
     }); 
    }]) 

但是,在做這...

你有沒有看響應攔截$http文檔中?

它看起來更適合認證purpouses,你可以在那裏注入服務。

+1

我確實最終配置了'$ http'而不是'$ httpProvider',就我的用例而言,它提供了完全相同的值。謝謝。 – 2013-07-24 22:22:42

+0

任何使用'angular.injector'並獲得相同的服務實例的方法,您將調用'config(...)'方法使用該模塊? – 2013-08-08 20:30:04

0

據我所知,您可以將它注入到配置中的函數中。如果他們沒有使用我的身份驗證服務登錄,我使用類似的截取請求。

.config(['$httpProvider',function ($httpProvider) { 
    var authRequest= ['customAuthService', function(customAuthService) { 
     if(customAuthService.isLoggedIn){ 
      data['api_key'] = {token: @token}; 
     } 
    }]; 
    $httpProvider.defaults.transformRequest.push(authRequest); 
}]); 
+0

不工作,讀取請求轉換器的方法期望回調,而不是數組,所以我得到一個'TypeError:對象不是函數'。 – 2013-05-07 05:12:01