简体   繁体   中英

How to use Angular.js service instance inside module config and keep the same instance

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM