2017-09-14 146 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);' –