2016-07-07 70 views
1

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

我有我的系统设置类似如下:

Boot.ts

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

MyViewResolver.ts

@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,所以我需要确保该提供者也被定义并可用于注入器。

我希望所有这些服务都由bootstrap“提供”,以便将来我可以在每个系统的基础上提供我的任何服务的备用版本。

供参考,这是角的核心ViewResolver

view_resolver.ts(Angular2核心):

import {Injectable, ViewMetadata, ComponentMetadata,} from '@angular/core'; 
import {ReflectorReader, reflector} from '../core_private'; 
import {Type, stringify, isBlank, isPresent} from '../src/facade/lang'; 
import {BaseException} from '../src/facade/exceptions'; 
import {Map} from '../src/facade/collection'; 

@Injectable() 
export class ViewResolver { 
    constructor(private _reflector: ReflectorReader = reflector) {} 

    resolve(component: Type): ViewMetadata { 
     ... stuff here ... 
    } 
} 

回答

2

你可以尝试用useFactory配置类:

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

谢谢,这工作的魅力。它没有使用与我的主引导应用程序相同的“提供程序”堆栈,但我仍然可以覆盖该级别的依赖关系,因此适用于我的使用!再次感谢。 – TimS