3

I have the following factory definition in my angularjs spa:

(function () {
  'use strict';

  angular.module('snApp')
  .factory('Auth', ['$http', 'localStorageService', function ($http,     localStorageService) {

   //code goes here
  }]);
})();

and then in my config for my app, i have the following http interceptor setup:

var app = angular.module('snApp', ['ui.router', 'LocalStorageModule', ])
.config(['$logProvider', '$stateProvider', '$urlRouterProvider', '$httpProvider',     '$provide', function ($logProvider, $stateProvider, $urlRouterProvider, $httpProvider,     $provide) {

    // Intercept http calls.
  $provide.factory('RequestHttpInterceptor', function ($q, Auth) {
      return {
          // On request success
          request: function ($config) {
              if (Auth.user) {
                  $config.headers['XToken'] = Auth.user.token;
              }
              return $config;
          }
      };
  });
  // Add the interceptor to the $httpProvider.
  $httpProvider.interceptors.push('RequestHttpInterceptor');
}]);

When I run the app, I get the following error:

Uncaught Error: [$injector:cdep]

I think it has something to do with the $http in my Auth, because if I remove that then it works, but I need it!

If someone can help me understand what im doing wrong, that would be fantastic!

2 Answers 2

5

Ok, I figured it out. Since its a http interceptor, angular doesn't like the fact that you are passing in $http to your factory - which makes sense, because if you call $http in an http interceptor it will invoke the interceptor, which will invoke the $http, etc etc getting this infinite loop.

Luckily I just needed a property in the factory so i abstracted that out of the Auth factory so that $http wasnt needed. There are other ways to do it, but this was the best solution for me.

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

Comments

2

You can still inject the $injector and create the $http when required. See here for some examples.

Another option is to emit/broadcast a message and capture this elsewhere (for example, as part of a run.)

Comments

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.