1

I have my request interceptor like below :

var requestFactory = angular.module('queryParamsModule', [])
        .factory('headerInterceptor', function($injector) {

          return {
            request: requestInterceptor
          };

          function requestInterceptor(req) {
              var accessToken;
              $injector.get('tokenService').accessToken().then(function(res) {
                accessToken = res.access_token;
                console.log(accessToken);  >>>>> accessToken is populated fine!
                req.headers = _.extend({
                  'Authorization': 'Bearer ' + accessToken
                }, req.headers);
              }, function(e) {
                // error
              });

            return req;
          }

        })
        .config(function($httpProvider) {
          $httpProvider.interceptors.push('headerInterceptor');
        });

      return queryParamsFactory;

The issue here is, angular doesnt wait for the Authorization Header to be added in request and pushes the interceptor before adding Authorization header.

Is there a way I can make my header interceptor part of the promise which is resolved after accessToken promise is complete?

1 Answer 1

3

As the manual says,

request: interceptors get called with a http config object. The function is free to modify the config object or create a new one. The function needs to return the config object directly, or a promise containing the config or a new config object.

So it should be:

  function requestInterceptor(req) {
      return $injector.get('tokenService').accessToken().then(function(res) {
        ...
        return req;
      }, function(e) { ... });
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Worked like charm. Thanks much!

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.