简体   繁体   中英

Circular dependency found in angular js

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

    }


})();

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 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM