我正在尝试在我的应用程序模块配置中使用一项服务,并且一些研究表明 I need to do it using an injector .
这工作得很好,除了当服务被加载到 Controller 内部时,它不再是与先前由注入(inject)器加载的实例相同的实例。
有谁知道如何获取同一个实例?或者有更好的方法吗?
我创建了一个 plnkr 来显示行为:http://plnkr.co/edit/BGUa3H
最佳答案
来自doc - 单例服务
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.
这意味着如果你对单个注入(inject)器执行 injector.get,它总是会像这样返回单例
var injector = angular.injector(['app.services']);
var singletonService1 = injector.get('singletonService');
var singletonService2 = injector.get('singletonService');
console.log(singletonService1 === singletonService2) // prints true
但是,如果您同时将它注入(inject)另一个 Controller ,则会创建一个全新的实例。
希望对您有所帮助。
关于javascript - 如何在模块配置中使用 Angular.js 服务实例并保持相同的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18136207/