0

MapServiceというインターフェイスと、GoogleMapsServiceLeafletMapServiceという2つの実装があるとします。私は、パッケージ(またはAngular2?)が、開発者ではなく必要な実装を呼びたいと思っています。角度の制御反転(IoC)を実行する

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

どのように私はそれを達成することができます:私は、サービスの種類は、インターフェース(そう、実装に依存しない)ようにしたいコンポーネントに、意味

export interface MapService { 
//define my API 
} 

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

?あなたはモジュールスコープで同じことを行うことができます

import { Component } from '@angular/core'; 
import { MapService } from './map.service'; 
import { GoogleMapsService } from './google-maps.service'; 

@Component({ 
    template : `...`, 
    providers: [ 
     { provide: MapService, useClass: GoogleMapsService } 
    ] 
}) 

export class MyComponent { 

    constructor(private googleMapsService : MapService) { 
    } 
} 

注:

+0

あなたは公式の[ドキュメント]を見たことがあります(https://angular.io/docs/ts/latest/guide/dependency- injection.html)? – Saravana

+0

DIはIoCの一種ですか?具体的に何をしたいですか? – Saravana

+1

サービスを提供するときにトークンを使用し、 '@Inject(theToken)private googleMapsService:MapService)'を使用します。しかし実際には、これは99%の時間では必要なく、具体的なクラスを嘲笑することはJS/TSの問題ではありません。 –

答えて

2

したがって、@ jb-nizetの素晴らしいコメントに基づいています。私はInjectionTokenを使って欲しいことをしました。ここでは、コードスニペットです:

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 
} 

とコンポーネント:

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

は、プロバイダの配列で、次の構文を使用します。

+0

あなたの解決策は動作しません! 'TS2693: 'MapService'はタイプのみを参照しますが、ここで値と​​して使用されています。 ' – Mitchapp

+2

AFAIKインタフェースをトークンとして使用することはできません – yurzui

関連する問題