2017-09-14 125 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"); 
    } 
})(); 

正如你可以看到,返回的配置對象之前,我想處理包含我需要添加到標題的附加數據的一些事件。
完全可能嗎?

回答

1

是的,你可以做到這一點,回到你的承諾var deferred = $q.defer();,比當異步方法完成,就可以解決您的更新配置:

  '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; 
      } 

更多您可以在AngularJS Interceptors

+0

閱讀感謝您發表評論Matej,但抱歉,我不完全明白。一個服務如何幫助我在這裏? – ashilon

+0

你不需要服務,你不返回配置,但你返回'promise'。等待事件發生時,然後您可以解析更新後的配置。 –

+0

您返回'promise',但真正的返回是在這個代碼中'deferred.resolve(config);' –