问题描述
我有一个MetaManager类:
I have a MetaManager class:
@Injectable()
export class MetaManager{
constructor(private handlers:Handler[]){
console.log(handlers);
}
}
此类需要一个 Handler []
才能注册为处理程序.然后,当我获得一些元数据时,我在处理程序数组中循环查看哪个可以处理我的元条目.
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.
话虽这么说,问题是我无法在main.ts中提供一个类数组作为config,这是我尝试过的(以及不起作用的地方):
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):
在MetaManager中使用字符串条目(带有 @Provide('HANDLERS')
注释)
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}) ]);
使用 Handler []
类提供程序:
bootstrap(AppComponent, [MetaManager, provide(Handler[], [DebugHandler])]);
我想提供一个类数组,因为 MetaManager
将来将需要有多个处理程序,通知,错误等...
I want to provide a class array because MetaManager
will need to have more than one Handler in the future, notification, error, etc...
使用多提供程序给了我没有Array的提供程序!(ApiService-> MetaManager->数组)
错误:
Using multi provider gives me a No provider for Array! (ApiService -> MetaManager -> Array)
Error:
meta-manager.ts:
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})]);
推荐答案
在为 Handler
类注册提供程序时,可以使用 multi
属性:
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);
}
}
以下是相应的插件: https://plnkr.co/edit/UBIvWfOvAmo4XO2ohbID?p=预览.本文可能会让您感兴趣:
Here is the corresponding plunkr: https://plnkr.co/edit/UBIvWfOvAmo4XO2ohbID?p=preview.This article could interest you:
这篇关于注入类数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!