Handling AngularJS events in an interceptor

198 Views Asked by At

Is it possible to have an interceptor wait for some event before sending the request to the server?

Here is the code of the interceptor:

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

As you can see, before returning the config object, i want to handle some event that contains additional data that I need to add to the headers.
Is it at all possible?

1

There are 1 best solutions below

3
On

Yes, you can do that,return your promise var deferred = $q.defer();, than when async method finish, you can resolve your updated config :

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

More you can read in AngularJS Interceptors