-1

got this error "Error: [$injector:cdep] Circular dependency found: $cookies <- $cookies <- AuthService"

with following code

'use strict';

angular.
  module('core.auth').
  factory('AuthService', [ '$http', '$rootScope', 'ConfigService', '$cookies',
    function AuthService($http, $rootScope, ConfigService, $cookies) {
      const service = {};

      service.Login = Login;
      service.SetCredentials = SetCredentials;
      service.ClearCredentials = ClearCredentials;

      return service;

      function Login(username, password, callback) {
        $http.post(ConfigService.LOGIN_API, { username: username, password: password })
           .success(function (response) {
               callback(response);
           });
      }

      function SetCredentials(username) {
        $rootScope.globals = {
          currentUser: {
            username: username
          }
        };

        $cookies.put('globals', $rootScope.globals);
      }

      function ClearCredentials() {
        $rootScope.globals = {};
        $cookies.remove('globals');
      }
    }
]);

and i'm use this service in login component

'use strict';

angular.
  module('login').
  component('login', {
    templateUrl: 'dist/components/login/login.template.html',
    controller: ['$location', 'AuthService', '$log',
      function LoginController($location, AuthService, $log) {

      (function initController() {
          // reset login status
          AuthService.ClearCredentials();
        }());

        this.login = () => {
          AuthService.Login(this.username, this.password, (response) => {
            if (response.success) {
              $log.log(response);
              $log.log('Login successful', true);
              AuthService.SetCredentials(this.username);
              $location.path('#!/products');
            } else {
              $log.log(response)
            }
          })
        }

      }
    ],

    controllerAs: 'vm'
});

can't understand whats wrong with my code... If remove $cookies from here, it's working perfectly. Maybe solution is write own cookies service? :)

vanless
  • 303
  • 1
  • 3
  • 13
  • It's hard to diagnose your problem without seeing your other services. If you take time and isolate your problem in a Plnkr, someone on the site will probably help figure out your problem. – mcranston18 Oct 09 '16 at 17:15
  • Maybe I used the wrong tool for the purposes. I'm solved problem just replaced ngCookies -> ngStorage. Working fine :) – vanless Oct 10 '16 at 07:29

1 Answers1

0

A circular dependency is always the sign of mixing of concerns, which is a really bad thing.One of the authors of AngularJS, explains a nice solution on his awesome blog. In short, you probably have a third service hidden somewhere, which is the only part of your code really needed by the two others.

Don Jose
  • 1,448
  • 2
  • 13
  • 27