0

Why does i can't inject services like this?

service('actionService',function (sessionService) {
 this.doAction = function () {
  return 5;
 }
});
service('sessionService',function (userService) {
 this.get = function {
    if(userService.check()){
    //do other stuffs 
    }
  }

});
service('userService',function (actionService) {
  this.check = function () {
  actionService.doAction();
  if(x = 9){ 
    return true;
  }else{ 
   return false; 
  } 
  }
});

I get "Circular injection error" in console

how to handle this now ?

here a better code : http://pastebin.com/wS32UNCq

1 Answer 1

2

Before you can have an instance of actionService, you need to inject an instance of sessionService.

Before you can have an instance of sessionService, you need to inject an instance of userService.

Before you can have an instance of userService, you need to inject an instance of actionService.

It's a chicken or the egg problem... because Angular uses constructor injection, it can't instantiate a service until all of its dependencies are satisfied. But the dependencies go around in a circle, none of them can ever be instantiated.

To solve this problem, you will need to extract a shared dependency out to an additional service which can be instantiated without dependencies.

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

6 Comments

hey thanks mate, but can you please go ahead explaining the last part about **shared dependency ** if you have some example just to get what you are explaining me, thanks!
Sure, I don't mind. Can you explain to me first why the action service depends on the session service? It's a bit tricky to try to unravel without the real code in front of me.
sure later i'll try pasting the real code, anyway sessionService gets user profile by userService and sets the user session, then actionService checks (by sessionService) if user session exists and redirects not logged users....(in two words) ;P
OK, for the moment I'd like to take this in a very different direction. Are you using the AngularJS routing stuff to load your partials?
sure $routeProvider you mean? i'm using it
|

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.