Angular2 How can I implement the whole implementation of the interface to serve as a list?

I am learning Angular2 with Typescript and I have a problem.

I have two classes that have the same interface. How can I inject them into a service as a list?

I read about opaquetoken https://angular.io/docs/ts/latest/guide/dependency-injection.html#opaquetoken

But I don't know if I need to use this and how to use it.

export interface CheckerInterface {
    check(text : string) : boolean
}

export class Checker1 implements CheckerInterface {
    check(text : string) : boolean {
    //do something 
    return true;
}

export class Checker2 implements CheckerInterface {
    check(text : string) : boolean {
    //do something 
    return true;
}

@Injectable()
export class Service {

  constructor(private checkers: CheckerInterface[]) {  //??
      checkers.foreach( checker => checker.check(somestring));
  }

}

      

Thanks for any help!

+6


source to share


1 answer


You need to either add an array as a provider or use multi: true

in config provider

.

export const CHECKERS = new OpaqueToken('one');

@NgModule({
  providers: [
     { provide: CHECKERS, useValue: [new Checker1(), new Checker2()] },
  ]
})

      

Or

@NgModule({
  providers: [
     { provide: CHECKERS, useClass: Checker1, multi: true },
     { provide: CHECKERS, useClass: Checker2, multi: true },
  ]
})

      

The second option is probably preferable as you let Angular build them, allowing them to inject their own dependencies if needed.



Then you just need to use the token CHECKERS

when you type

import { Inject } from '@angular/core';
import { CHECKERS } from './wherever';

constructor(@Inject(CHECKERS) private checkers: CheckerInterface[]) { 

      

UPDATE

In corner 4, used instead of InjectionToken

OpaqueToken

export const CHECKERS = new InjectionToken<CheckerInterface>('CheckerInterface');

      

+2


source







All Articles