typescript - Haciendo Inversión de Control (IoC) en Angular
Consideremos que tenemos una interfaz llamada MapService, y dos implementaciones: GoogleMapsService y LeafletMapService. Quiero un paquete (¿o Angular2?) que llame a la implementación necesaria en lugar de los desarrolladores.
export interface MapService {
//define my API
}
@Injectable()
export class GoogleMapsService implements MapService {
//implement the API
}
Eso significa que, en el componente, quiero que el tipo del servicio sea la interfaz (para no depender de la implementación):
import { Component } from '@angular/core';
import { MapService } from './map.service';
import { GoogleMapsService } from './google-maps.service';
@Component({
template : `...`,
providers: [GoogleMapsService]
})
export class MyComponent {
constructor(private googleMapsService : MapService) { //notice the type of the service here
}
}
¿Cómo puedo lograr eso?
Respuesta #1
Entonces, basándome en el gran comentario de @jb-nizet, he logrado hacer lo que quiero usando InjectionToken. Aquí hay un fragmento de código:
import { Injectable, InjectionToken } from '@angular/core';
export const GOOGLE_MAPS_IMPL = new InjectionToken<MapService>('googleMapImpl');
export interface MapService {
//define the API
}
@Injectable()
export class GoogleMapsService implements MapService {
//implement the API
}
Y el componente:
import { Component, Inject } from '@angular/core';
import { MapService } from './map.service';
import { GoogleMapsService, GOOGLE_MAPS_IMPL } from './google-maps.service';
@Component({
template : `...`,
providers: [{ provide: GOOGLE_MAPS_IMPL, useClass: GoogleMapsService }]
})
export class MyComponent {
constructor(@Inject(GOOGLE_MAPS_IMPL) private googleMapsService : MapService) {
}
}
