Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
Angular2 ¿Cómo puedo inyectar toda la implementación de la interfaz al servicio como lista?

Estoy aprendiendo Angular2 con Typescript y tengo un problema.

Tengo dos clases que implementan la misma interfaz. ¿Cómo puedo inyectarlos en un servicio como una lista?

Leí sobre opaquetoken https://angular.io/docs/ts/latest/guide/dependency-injection.html#opaquetoken

Pero no sé si necesito usarlo y cómo usarlo.

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

Gracias por cualquier ayuda !

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Debe agregar la matriz como proveedor o usar multi: true en la configuración del provider .

 export const CHECKERS = new OpaqueToken('one'); @NgModule({ providers: [ { provide: CHECKERS, useValue: [new Checker1(), new Checker2()] }, ] })

O

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

El segundo es probablemente preferible, ya que permite que Angular los cree, lo que les permite inyectar sus propias dependencias si es necesario.

Entonces solo necesita usar el token CHECKERS cuando inyecte

 import { Inject } from '@angular/core'; import { CHECKERS } from './wherever'; constructor(@Inject(CHECKERS) private checkers: CheckerInterface[]) {

ACTUALIZAR

A partir de Angular 4, se usa InjectionToken en lugar de OpaqueToken

 export const CHECKERS = new InjectionToken<CheckerInterface>('CheckerInterface');
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!