我在引导中定义了一个@Injectable
服务。我希望在不使用构造函数注入的情况下获取服务实例。我尝试使用ReflectiveInjector.resolveAndCreate
,但这似乎创建了一个新实例。
我之所以要这样做,是因为我有一个由许多组件派生的基本组件。现在我需要访问一个服务,但是我不想将它添加到构造函数中,因为我不想在所有派生组件上注入服务。
我需要一个ServiceLocator.GetInstance<T>()
更新: RC5+:Storing injector instance for use in components的更新代码
发布于 2016-05-27 11:42:33
是的,ReflectiveInjector.resolveAndCreate()
创建了一个新的、未连接的注入器实例。
您可以插入Angulars Injector
实例,并使用
constructor(private injector:Injector) {
injector.get(MyService);
}
您还可以将Injector
存储在某个全局变量中,而不是使用这个注入器实例来获取提供的实例,例如,如https://github.com/angular/angular/issues/4112#issuecomment-153811572中所解释的。
发布于 2017-03-14 12:32:22
在使用ngModules的更新角中,可以在代码中的任何位置创建一个可用的变量:
在app.module.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);
发布于 2016-05-27 12:12:35
另一种方法是定义自定义装饰器(用于设置依赖注入的元数据的CustomInjectable
):
export function CustomComponent(annotation: any) {
return function (target: Function) {
// DI configuration
var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
var parentAnnotations = Reflect.getMetadata('design:paramtypes', parentTarget);
Reflect.defineMetadata('design:paramtypes', parentAnnotations, target);
// Component annotations / metadata
var annotations = Reflect.getOwnMetadata('annotations', target);
annotations = annotations || [];
annotations.push(annotation);
Reflect.defineMetadata('annotations', annotations, target);
}
}
它将利用来自父构造函数的元数据,而不是它自己的元数据。您可以在子类上使用它:
@Injectable()
export class SomeService {
constructor(protected http:Http) {
}
}
@Component()
export class BaseComponent {
constructor(private service:SomeService) {
}
}
@CustomComponent({
(...)
})
export class TestComponent extends BaseComponent {
constructor() {
super(arguments);
}
test() {
console.log('http = '+this.http);
}
}
有关更多细节,请参见此问题:
https://stackoverflow.com/questions/37482460
复制相似问题