0

I am trying to refactor my AngularJS application and introduce a login service. Currently my controller has methods like login(), logout(), getCurrentUser(), which make http requests and handle the user object. I want to move these functions into a service, because I need to call the getCurrentUser() method from multiple controllers.

I have written the following service:

angular.module('common.login', []).
    factory('loginService', function ($http) {

        return {
            user: null,
            error: null
        };
    });

So at the moment the service is not doing anything. However I get an error:

Uncaught Error: Circular dependency: loginService <- $http

If I remove the $http dependency from the callback function, then the service works. I have trouble understanding why there is a circular dependency. The loginService factory is injected into two places: A **main module's config callback ** and a **login module's controller callback **. The config callback configures a http interceptor, the login controller also uses the http services.

2
  • Hello lanoxx. Please post your controllers' signatures in order to understand the DI issue. Commented Apr 14, 2014 at 15:13
  • I would almost suggest making this a function on the rootScope instead of as a service. Commented Apr 14, 2014 at 15:14

1 Answer 1

1

The circular dependency is caused because you configure an httpInterceptor either to send some auth token or to intercept 401 error that depend on your login service that depend itself from the $http service.

Your httpInterceptor should not depend of your login service. For instance if you need to send a token, you could store it in localStorage when you login and then in your httpInterceptor read it from there instead of your loginService. If you need to logout the user when you get a 401 error then juste redirect the user to /logout instead of calling a logout method on your loginService.

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

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.