2013-05-07 9 views
5

でプロバイダとカスタムサービスミキシング:Angularjs docによると:私はそのようsomtehingやってみたいモジュールのconfig /実行

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

を、私は私のmoduleconfigブロックでそれを行うことができません、 $httpProviderのようなプロバイダが存在し許可されていないため、カスタムサービスは、そこに許可されていない、また私はrunブロックでそれを行うことができますので:

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

私は、 '$ httpProvider'の代わりに' $ http'を設定しました。これは、私のユースケースに関する限り、まったく同じ値を提供します。ありがとう。 –

+0

'angular.injector'を使い、' config(...) 'メソッドを呼び出すモジュールが使うサービスインスタンスを得る方法はありますか? –

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:オブジェクトは関数ではありません。 'というメッセージが表示されます。 –

関連する問題