首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在没有构造函数注入的情况下获取服务实例

在没有构造函数注入的情况下获取服务实例
EN

Stack Overflow用户
提问于 2016-05-27 11:34:19
回答 5查看 117.5K关注 0票数 122

我在引导中定义了一个@Injectable服务。我希望在不使用构造函数注入的情况下获取服务实例。我尝试使用ReflectiveInjector.resolveAndCreate,但这似乎创建了一个新实例。

我之所以要这样做,是因为我有一个由许多组件派生的基本组件。现在我需要访问一个服务,但是我不想将它添加到构造函数中,因为我不想在所有派生组件上注入服务。

我需要一个ServiceLocator.GetInstance<T>()

更新: RC5+:Storing injector instance for use in components更新代码

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2016-05-27 11:42:33

是的,ReflectiveInjector.resolveAndCreate()创建了一个新的、未连接的注入器实例。

您可以插入Angulars Injector实例,并使用

代码语言:javascript
运行
复制
constructor(private injector:Injector) {
  injector.get(MyService);
}

您还可以将Injector存储在某个全局变量中,而不是使用这个注入器实例来获取提供的实例,例如,如https://github.com/angular/angular/issues/4112#issuecomment-153811572中所解释的。

票数 93
EN

Stack Overflow用户

发布于 2017-03-14 12:32:22

在使用ngModules的更新角中,可以在代码中的任何位置创建一个可用的变量:

app.module.ts中添加此代码

代码语言:javascript
运行
复制
import { Injector, NgModule } from '@angular/core';

export let AppInjector: Injector;
    
export class AppModule {
  constructor(private injector: Injector) {
    AppInjector = this.injector;
  }
}

现在,您可以使用AppInjector在代码的任何地方找到任何服务。

代码语言:javascript
运行
复制
import { AppInjector } from '../app.module';

const myService = AppInjector.get(MyService);
票数 108
EN

Stack Overflow用户

发布于 2016-05-27 12:12:35

另一种方法是定义自定义装饰器(用于设置依赖注入的元数据的CustomInjectable ):

代码语言:javascript
运行
复制
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);
  }
}

它将利用来自父构造函数的元数据,而不是它自己的元数据。您可以在子类上使用它:

代码语言:javascript
运行
复制
@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);
  }
}

有关更多细节,请参见此问题:

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37482460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档