首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >装饰器的角度2依赖注入

装饰器的角度2依赖注入
EN

Stack Overflow用户
提问于 2016-04-24 09:43:33
回答 1查看 2K关注 0票数 1

有任何方法将服务依赖注入到@Component装饰中吗?

代码语言:javascript
复制
@Component({
    selector: injectedService.getPrefix() + 'my-component'
})
export class MyComponent { }

或者,如果不是,是否有可能将@Component子类注入到子类中以获得类似的结果?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-24 11:25:03

更新>= RC.5

代码语言:javascript
复制
@NgModule({
  ...
})
export class AppModule {
  ngDoBootstrap(moduleRef) {
    appInjector(moduleRef.injector);
  }
}

appInjector实现见下文

原始<= RC.5

Angular2不直接支持这一点。您可以将注射器存储在您的角度应用程序之外,然后从该应用程序中引用它,就像在https://github.com/angular/angular/issues/4112#issuecomment-153811572中演示作为https://github.com/angular/angular/issues/4112#issuecomment-153811572装饰器的解决方案一样。(Plunker example)

main.ts中,注入器被分配给appInjector

代码语言:javascript
复制
bootstrap(App, [
  Auth,
  HTTP_PROVIDERS,
  ROUTER_PROVIDERS,
  provide(LocationStrategy, {useClass: HashLocationStrategy})
]).then((appRef: ComponentRef) => {
  // store a reference to the application injector
  appInjector(appRef.injector);
});

app-injector.ts

代码语言:javascript
复制
let appInjectorRef: Injector;
export const appInjector = (injector?: Injector):Injector => {
    if (injector) {
      appInjectorRef = injector;
    }

    return appInjectorRef;
};

然后,您可以获得对注射器的引用,如

代码语言:javascript
复制
appInjector()...

如果组件是在bootstrap()完成之前创建的,这是行不通的。

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

https://stackoverflow.com/questions/36821535

复制
相关文章

相似问题

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