1
I’m having the http circular dependency problem at the angle.
I have seen other questions with similar subject, but the ways I have tried I have not yet managed to solve the problem..
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 execute this error is displayed,
[$injector:cdep] Circular dependency found: $http <- Authservice <- Authinterceptor <- $http <- $templateRequest <- $route
Authinterceptor needs Authservice to configure the request header, I think that internally it uses $http, this justifies the circular dependency error.. but I need the $http service in Authservice, to perform the Login and Logout requests...
Can someone help me?
Hi good afternoon, yeah. remove the login with $http is a solution, but then I would have to log in from another point, so I can’t concentrate this type of request ( login, logou ) in the same Factory.. but thanks for the answer, I think I’ll opt for that very thing..
– Fabio Moura
@Fabiomoura are two different scopes, authorization and authentication. You can have an authentication service with the methods of Sign in and Sign out, and another authorization service that checks if the token is loaded and valid. Tie the authentication service to a route/status, and configure the Interceptor to ignore the required endpoints.
– OnoSendai