自定义ViewResolver和依赖注入

时间:2016-07-07 21:02:36

标签: dependency-injection angular angular2-services

我试图创建一个自定义element.replaceChild课程(扩展角度的内置课程)以增强我的系统'使用自定义服务的样式元数据(我从外部系统加载我的样式)。但是,我遇到了依赖注入系统和ViewResolver的问题。

我的系统设置如下:

Boot.ts

ViewResolver

MyViewResolver.ts

bootstrap(App, [
    MyStyleService,   // my custom service
    SomeOtherService, // another custom service used by MyStyleService
    {
        provide: ViewResolver,
        useClass: MyViewResolver  // my custom ViewResolver
    }
])

但是在@Injectable() export class MyViewResolover extends ViewResolver { constructor( private _reflector: ReflectorReader, // I want to reference 'StyleService' from the providers array in boot.ts private _styleService: StyleService ) { super(_reflector); } public resolve(comopnent: Type) { let meta: ViewMetadata = super.resolve(component); let styles = this._styleService.someMethod(meta); } } 内,MyViewResolver尚未注入,目前为this._styleService。应该注意的是undefined还取决于另一个注入的服务MyStyleService,因此我需要确保该提供程序也已定义并可用于注入器。

我希望所有这些服务都是"提供"通过引导程序,以便将来我可以在每个系统的基础上提供任何服务的备用版本。

作为参考,这是角度核SomeOtherService

view_resolver.ts (Angular2核心):

ViewResolver

1 个答案:

答案 0 :(得分:2)

您可以尝试使用useFactory配置您的课程:

bootstrap(App, [
  MyStyleService,
  SomeOtherService,
  {
    provide: ViewResolver,
    useFactory: (_reflector: ReflectorReader, styleService: StyleService) => {
      return MyViewResolver(_reflector, _styleService);
    },
    deps: [ ReflectorReader, StyleService ]
  }
]);