2

I am trying to use an service inside my app module config and a little research pointed that I need to do it using an injector.

This works pretty fine, except that when the service is loaded inside the controllers it is not the same instance anymore as the one previously loaded by the injector.

Does anyone know how to get the same instance? Or is there a better way to do it?

I created a plnkr to show the behavior: http://plnkr.co/edit/BGUa3H

Community
  • 1
  • 1
Felipe Sabino
  • 17,825
  • 6
  • 78
  • 112
  • You should check this out - http://stackoverflow.com/questions/15286588/how-to-inject-dependency-into-module-configconfigfn-in-angular – callmehiphop Aug 08 '13 at 21:30
  • @callmehiphop yap, but I really need it in my config as I need it to configure my routes properly.. actually, the goal is to be able to use it kind of like this http://plnkr.co/edit/lfDyLE (using ui-router + authentication with the resolve feature calling my secutiry service) – Felipe Sabino Aug 08 '13 at 21:41

1 Answers1

0

From the doc - Services as singletons

All Angular services are application singletons. This means that there is only one instance of a given service per injector. Since Angular is lethally allergic to global state, it is possible to create multiple injectors, each with its own instance of a given service, but that is rarely needed, except in tests where this property is crucially important.

It mean if you do injector.get for a single injector, it will always returns the singleton like this

var injector = angular.injector(['app.services']);
var singletonService1 = injector.get('singletonService');
var singletonService2 = injector.get('singletonService');
console.log(singletonService1 === singletonService2) // prints true

However if you inject it to another the controller in the meantime, a brand new instance will be created.

Hope it helps.

zs2020
  • 53,766
  • 29
  • 154
  • 219
  • hmmm I haven't pay attention to the `per injector` part, so how can I access the injector used to resolve the depencies for my controllers, instead of having to create a new one? – Felipe Sabino Aug 08 '13 at 22:12