简体   繁体   English

如何在模块配置中使用Angular.js服务实例并保持相同的实例

[英]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 我创建了一个plnkr来显示该行为: http ://plnkr.co/edit/BGUa3H

From the doc - Services as singletons 文档 -服务作为单例

All Angular services are application singletons. 所有Angular服务都是应用程序单例。 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. 由于Angular对全局状态具有致命的过敏性,因此可以创建多个注入器,每个注入器具有给定服务的自己的实例,但这很少需要,除非在此属性至关重要的测试中。

It mean if you do injector.get for a single injector, it will always returns the singleton like this 这意味着,如果您为单个喷射器执行jector.get,它将始终像这样返回单例

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. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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