2017-09-14 10 views
0

インターセプタは、リクエストをサーバに送信する前に、あるイベントを待機することはできますか?ここで インターセプタのAngularJSイベントの処理

はインターセプタのコードです:あなたが見ることができるように

(function() { 
    "use strict"; 
    angular.module("fuse").config(config); 

    /** @ngInject */ 
    function config($httpProvider, $provide) { 
    $provide.factory("httpInterceptor", function($q, $rootScope) { 
     return { 
     request: function(config) { 
      // I need to wait for some event, read its argument and add this argument to the headers 

      return config || $q.when(config); // Only return after handling the event 
     }, 
     response: function(response) { 
      console.log("Data Count: " + response.data.length); 
      return response || $q.when(response); 
     } 
     }; 
    }); 

    $httpProvider.interceptors.push("httpInterceptor"); 
    } 
})(); 

は、configオブジェクトを返す前に、私は、ヘッダーに追加する必要がある追加データが含まれているいくつかのイベントを処理します。
これはすべて可能ですか?

はい、あなたは非同期メソッドの仕上げよりも、あなたの約束 var deferred = $q.defer();を返し、それを行うことができ、あなたの更新コンフィグ解決することができます

答えて

1

:あなたはAngularJS Interceptors

+0

で読むことができます

 'request': function(config) { var deferred = $q.defer(); someAsyncService.doAsyncOperation().then(function() { // Asynchronous operation succeeded, modify config accordingly ... deferred.resolve(config); }, function() { // Asynchronous operation failed, modify config accordingly ... deferred.resolve(config); }); return deferred.promise; } 

詳しいコメントありがとうございましたマテイ、申し訳ありませんが、私は完全に理解していません。サービスは私をどのように助けますか? – ashilon

+0

サービスは必要ありませんが、configを返さずに 'promise'を返します。そして、イベントが終了すると、イベントを待ってから、更新された設定を解決することができます。 –

+0

'promise'を返しますが、実際の戻り値はこのコードにあります。' deferred.resolve(config); ' –