MapService
인터페이스와 GoogleMapsService
및 LeafletMapService
의 두 가지 구현이 있다고 가정 해보십시오. 패키지 (또는 Angular2?)가 개발자가 아닌 필요한 구현을 호출하기를 원합니다. 구성 요소에서 나는 서비스의 유형은 인터페이스가되고 싶어요 의미각도로 반전 제어 (IoC) 수행하기
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: [GoogleMapsService]
})
export class MyComponent {
constructor(private googleMapsService : MapService) { //notice the type of the service here
}
}
가 어떻게 그것을 달성 할 수 있는가? 이 모듈 범위에서 같은 일을 할 수
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) {
}
}
참고 :
당신이 공식 [문서]를 본 적이 (https://angular.io/docs/ts/latest/guide/dependency- 여기에 코드 조각입니다 injection.html)? – Saravana
DI가 IoC의 형태가 아닌가요? 구체적으로 무엇을하고 싶습니까? – Saravana
서비스를 제공 할 때 토큰을 사용하고'@Inject (theToken) private googleMapsService : MapService)'를 사용하십시오. 하지만 실제로는 99 %의 시간이 필요하지 않으며 JS/TS에서는 구체적인 클래스를 조롱하는 것이 문제가되지 않습니다. –