我有一个@Injectable
Bootstrap 中定义的服务。我想在不使用构造函数注入的情况下获取服务的实例。我尝试使用ReflectiveInjector.resolveAndCreate
但这似乎创建了一个新实例。
我尝试这样做的原因是我有一个从许多组件派生的基本组件。现在我需要访问服务,但我不想将其添加到构造函数中,因为我不想将服务注入到所有派生组件上。
TLDR:我需要一个ServiceLocator.GetInstance<T>()
UPDATE:更新了 RC5+ 的代码:存储注入器实例以在组件中使用
在使用 ngModules 的更新版 Angular 中,您可以在代码中的任何位置创建可用的变量:
将此代码添加到应用程序模块.ts
import { Injector, NgModule } from '@angular/core';
export let AppInjector: Injector;
export class AppModule {
constructor(private injector: Injector) {
AppInjector = this.injector;
}
}
现在,您可以使用AppInjector
在代码的任何位置查找任何服务。
import { AppInjector } from '../app.module';
const myService = AppInjector.get(MyService);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)