2

Tring to add interceptor header for my every request, however, it is giving me below error.

Uncaught Error: [$injector:cdep] Circular dependency found: $http <- Auth <- httpRequestInterceptor <- $http <- $templateRequest <- $route

app.js

var app= angular.module('myDemoApp',['ngRoute'])


app.factory('httpRequestInterceptor', ['Auth', function (Auth) {
  return {
    request: function (config) {

      config.headers['x-access-token'] = Auth.getToken();
      return config;
    }
  };
}]);

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

Auth Service

(function () {
    'use strict';

    myDemoApp.factory('Auth', ['$http', '$window', Auth]);

    /******Auth function start*****/
    function Auth($http, $window) {
        var authFactory = {};

        authFactory.setToken = setToken;
        authFactory.getToken = getToken;
        return authFactory;


        /*setToken function start*/
        function setToken(token) {

            if (token) {
                $window.localStorage.setItem('token', token);
            } else {
                $window.localStorage.removeItem('token');
            }

        }

        /*getToken function start*/
        function getToken() {
            return $window.localStorage.getItem('token')
        }

    }


})();
0

1 Answer 1

6

You can't do this because.

  1. You have created httpRequestInterceptor which intercepts all $http requests.

  2. Now, you are passing Auth in the httpRequestInterceptor.

  3. If you'll see, Auth uses $http request inside itself.

  4. So, your interceptor can itself cause a http request using Auth.

Hence, its circular error and angularjs wont allow you to do that !

Remove $http from Auth factory OR dont insert a service into interceptor which itself uses $http.

I hope you got, how the infinite loop chain being created, hence a circular dependency error !

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

1 Comment

Thanks. I have remove $http service and it is working fine now.

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.