Inject class array

我的未来我决定 提交于 2019-12-24 13:06:38

问题


I have a MetaManager class:

@Injectable()
export class MetaManager{

    constructor(private handlers:Handler[]){
        console.log(handlers);
    }
}

this class needs a Handler[] to register as handlers. Than, when I get some metadata, I loop in my handlers array to see which one can handler my meta entry.

Having said that, problem is that I can't provide an array of class as config in main.ts, here is what I have tried (and what did not work):

Using String entry (with a @Provide('HANDLERS') annotation in MetaManager:

`bootstrap(AppComponent, [MetaManager,provide('HANDLERS', {useValue: [DebugHandler]}) ]);`

Using an interface to provide handlers:

export const HANDLERS: HandlerConfig = {handlers: [<Handler>DebugHandler]};

bootstrap(AppComponent, [MetaManager, provide(HandlerConfig, {useValue: HANDLERS}) ]);

Using a Handler[] class provider:

bootstrap(AppComponent, [MetaManager, provide(Handler[], [DebugHandler])]);

I want to provide a class array because MetaManager will need to have more than one Handler in the future, notification, error, etc...

EDIT:

Using multi provider gives me a No provider for Array! (ApiService -> MetaManager -> Array) Error:

meta-manager.ts:

@Injectable()
export class MetaManager{

    constructor(private handlers:Handler[]){
        console.log(handlers);
    }
}

main.ts:

bootstrap(AppComponent,
    [   MetaManager,
        provide(Handler, {useClass: DebugHandler, multi: true}),
        provide(Handler, {useClass: NotificationHandler, multi: true})]);

回答1:


You could use the multi attribute when registering your providers for the Handler class:

bootstrap(AppComponent, [
  MetaManager,
  provide(Handler, { useClass: DebugHandler, multi: true }),
  provide(Handler, { useClass: OtherHandler, multi: true })
]);

This way, you will be able to inject this way:

@Injectable()
export class MetaManager{
  constructor(@Inject(Handler) private handlers:Handler[]){
    console.log(handlers);
  }
}

Here is the corresponding plunkr: https://plnkr.co/edit/UBIvWfOvAmo4XO2ohbID?p=preview. This article could interest you:

  • http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html


来源:https://stackoverflow.com/questions/36205892/inject-class-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!