Circular Dependency http 'Circular dependency found: $ http - AuthService - AuthInterceptor - $ http - $ templateRequest - $ route'

1

I'm having the problem of circular http dependency in the angular.

I've seen other questions with similar subject matter, but the ways I've tried have not been able to resolve the problem yet.

My Code:

var app = angular.module("app", [
    "ngRoute",
    "ngResource",
    "toastr",
    "ngStorage"    
    ]);

app.factory( "AuthService", AuthService );
app.factory( "AuthInterceptor", AuthInterceptor );


app.config(["$httpProvider", function( $httpProvider){

        $httpProvider.interceptors.push("AuthInterceptor");

}]);

app.run(function ($rootScope, $location, AuthService) {

    $rootScope.$on('$routeChangeStart', function (event, next, current) {

        if (!AuthService.getToken()) {

          $rootScope.$evalAsync(function () {
            $location.path('/signin');
          })
        }
    });

});

function AuthService($localStorage, $http, $q) {

  return {
    getToken : function () {
      return $localStorage.token;
    },
    setToken: function (token) {
      $localStorage.token = token;
    },
    login : function (data) {
      $http.post(URL+"user/login", data);
    },
    logout : function (data) {
      delete $localStorage.token;
      $q.when();
    }
  };
}



function AuthInterceptor($location, AuthService, $q ) {

  return {
    request: function(config) {
      config.headers = config.headers || {};

      if (AuthService.getToken()) {
        config.headers['Authorization'] = 'Bearer ' + AuthService.getToken();
      }

      return config;
    },

    responseError: function(response) {

      if (response.status === 401 || response.status === 403) {
        $location.path('/signin');
      }

      return $q.reject(response);
    }
  }
} 

When I run this error appears,

[$ injector: cdep] Circular dependency found: $ http -

asked by anonymous 15.02.2017 / 02:58

2 answers

1

@OnoSendai after refactoring with his separation of responsibilities board, worked perfectly. Create an AuthorizeService with getToken and setToken, and the AuthenticService that log in, logout .. I can thus inject the $ http provider into the AuthenticService normally,

In the end it was like this, sharing, it might help other people,


var app = angular.module("app", [
    "ngRoute",
    "ngResource",
    "toastr",
    "ngStorage"    
    ]);

app.factory( "AuthenticService", AuthenticService );
app.factory( "AuthorizeService", AuthorizeService );
app.factory( "AuthInterceptor", AuthInterceptor );

app.config(["$httpProvider", function($httpProvider){

        $httpProvider.interceptors.push("AuthInterceptor");

}]);

app.run(function ($rootScope, $window, AuthorizeService) {
   $rootScope.$on('$routeChangeStart', function (event, next, current) {
        if (!AuthorizeService.getToken()  ) {

            event.preventDefault();

            $rootScope.$evalAsync(function () {            
                $window.location.href = "/login.php";            
            });
        };  

    });

});

function AuthenticService($localStorage, AuthorizeService, $http, $q) {

  return {
    login : function (data) {
      $http.post(URL+"auth/login", data)
      .then(function(data){

            var result = null;

            if (data && data.data instanceof Object) {

                result = data.data;

                if ( result["success"] ) {

                    $localStorage.token = result["token"]; 
                    $window.location.href = '/projeto/frontend/';
                    AuthorizeService.setToken(data.data);

                } else if ( result["error"] ) {

                    alert("Não foi possível autenticar, " + result["msg"] );

                } else {

                    alert("Ocorreu um erro no servidor" );
                }
            }   

      });
    },

    logout : function (data) {
      delete $localStorage.token;
      $q.when();
    }
  };
}


function AuthorizeService($localStorage, $window, $q) {

  return {

    getToken : function () {
      return $localStorage.token;
    },

    setToken: function (data) {         
        if (data instanceof Object) {
            if ( data["success"] ) {
                $localStorage.token = data["token"]; 
                $window.location.href = '/projeto/frontend/';

            } else if ( data["error"] ) {
                alert("Não foi possível autenticar, " + data["msg"] );
            } else {
                alert("Erro" );
            }
        }          
    }

  };
}

function AuthInterceptor($location, AuthorizeService, $q ) {

  return {

    request: function(config) {
      config.headers = config.headers || {};

      if (AuthorizeService.getToken()) {
        config.headers['Authorization'] = AuthorizeService.getToken();
      }

      return config;
    },

    responseError: function(response) {

      if (response.status === 401 || response.status === 403) {
        $location.path('/signin');
      }

      return $q.reject(response);
    }
  }
}


Thank you partner!

    
16.02.2017 / 17:09
0

AuthService has a method, login() , which is not used anywhere in the code. It is also the only snippet that uses the $http provider.

Solution : Remove, from AuthService , the injection of the $http service and the login() function.

    
15.02.2017 / 15:04