Website-Suche

TypeScript - Durchführung der Inversion of Control (IoC) in Angular


Betrachten wir, dass wir ein Interface namens MapService haben und zwei Implementierungen: GoogleMapsService und LeafletMapService. Ich möchte ein Paket (oder Angular2?), das die benötigte Implementierung aufruft, anstatt dass die Entwickler dies tun.

export interface MapService {
//define my API
}

@Injectable()
export class GoogleMapsService implements MapService {
//implement the API
}

Das bedeutet, dass ich in der Komponente möchte, dass der Typ des Dienstes das Interface ist (also nicht von der Implementierung abhängt):

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

Wie kann ich das erreichen?

Antwort #1

Also basierend auf dem großartigen Kommentar von @jb-nizet; ich habe es geschafft, mit InjectionToken das zu tun, was ich möchte. Hier ist ein Codeausschnitt:

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
}

Und die Komponente:

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

Verwandte Artikel