Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在拦截器中处理AngularJS事件_Angularjs_Angular Http Interceptors - Fatal编程技术网

在拦截器中处理AngularJS事件

在拦截器中处理AngularJS事件,angularjs,angular-http-interceptors,Angularjs,Angular Http Interceptors,是否可以让拦截器在将请求发送到服务器之前等待某个事件 以下是拦截器的代码: (function() { "use strict"; angular.module("fuse").config(config); /** @ngInject */ function config($httpProvider, $provide) { $provide.factory("httpInterceptor", function($q, $rootScope) { ret

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

以下是拦截器的代码:

(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.deferred(),而非异步方法完成时,您可以解析更新的配置:

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

您可以在

中阅读更多内容,谢谢您的评论,Matej,但很抱歉,我没有完全理解。服务在这里如何帮助我?您不需要服务,您不返回配置,但您返回
promise
。然后等待某个事件,当事件完成时-然后您可以解析更新的配置。您返回
promise
,但真正的返回是在这个代码
deferred.resolve(配置)