angularangular2-injection

Inject class array


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})]);

Solution

  • 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: