0

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 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your comment Matej, but sorry I don't quite fully understand. How can a service help me here?
You do not need service, you do not return config, but you return promise. And you wait for some event, when then event finish - then you can resolve updated config.
You return promise, but real return is in this code deferred.resolve(config);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.