【问题标题】:Handling AngularJS events in an interceptor在拦截器中处理 AngularJS 事件
【发布时间】:2017-09-14 23:36:43
【问题描述】:

是否可以让拦截器在向服务器发送请求之前等待某个事件?

拦截器的代码如下:

(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");
  }
})();

如您所见,在返回配置对象之前,我想处理一些包含我需要添加到标头的附加数据的事件。
有可能吗?

【问题讨论】:

    标签: angularjs angular-http-interceptors


    【解决方案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阅读更多内容

    【讨论】:

    • 感谢您的评论 Matej,但很抱歉我不太明白。服务如何帮助我?
    • 你不需要服务,你不返回配置,但你返回promise。然后你等待一些事件,然后事件完成 - 然后你可以解决更新的配置。
    • 您返回promise,但真正的返回在此代码deferred.resolve(config);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多