在没有构造函数注入的情况下获取服务实例 [英] Getting instance of service without constructor injection
问题描述
我在引导程序中定义了@Injectable
服务.我想在不使用构造函数注入的情况下获取服务的实例.我尝试使用ReflectiveInjector.resolveAndCreate
,但这似乎创建了一个新实例.
I have a @Injectable
service defined in bootstrap. I want to get the instance of the service without using constructor injection. I tried using ReflectiveInjector.resolveAndCreate
but that seem to create a new instance.
我要这样做的原因是我有一个由许多组件派生的基本组件.现在,我需要访问服务,但是由于不想将服务注入所有派生组件,所以我不想将其添加到ctor中.
The reason I'm trying to do is I have a base component derived by many components. Now I need to access a service but I don't want to add it to the ctor because I don't want to inject the service on all of the derivative components.
TLDR:我需要一个ServiceLocator.GetInstance<T>()
TLDR: I need a ServiceLocator.GetInstance<T>()
更新:RC5 +的更新代码:存储用于组件的喷油器实例
UPDATE: Updated code for RC5+: Storing injector instance for use in components
推荐答案
是的,ReflectiveInjector.resolveAndCreate()
创建一个新的且未连接的注射器实例.
Yes, ReflectiveInjector.resolveAndCreate()
creates a new and unconnected injector instance.
您可以注入Angulars Injector
实例,并使用它从中获取所需的实例
You can inject Angulars Injector
instance and get the desired instance from it using
constructor(private injector:Injector) {
injector.get(MyService);
}
您还可以将Injector
存储在某些全局变量中,然后使用此注入器实例来获取提供的实例,例如,如
You also can store the Injector
in some global variable and than use this injector instance to acquire provided instances for example like explained in https://github.com/angular/angular/issues/4112#issuecomment-153811572
这篇关于在没有构造函数注入的情况下获取服务实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!