2017-02-13 2 views
7

나는이 작업을 수행 할 수 있습니다 대신의각도 2 : 대신 생성자 주입의 속성 주입

export class BaseComponent { 
protected config: IConfig; 

@Inject(AppConfig) protected appConfig: AppConfig; 

constructor() 
{ 
    this.config = this.appConfig.getConfig();  
} 

:

export class BaseComponent { 
config: IConfig; 

constructor(
    private appConfig: AppConfig, 
    ) 
{ 
    this.config = appConfig.getConfig();  
} 

목표는 생성자 서명을 단순화하기 위해, 그래서 모든 하위 구성 요소를하지에 생성자에 appConfig를 지정해야합니다. 그래서 BaseComponent에서 상속 구성 요소는 다음과 같다 없습니다 :

@Component({ 
    selector: 'sport-templates', 
    templateUrl: 'templates.component.html', 
    styleUrls: [ 'templates.component.scss' ], 
    encapsulation: ViewEncapsulation.None 
}) 
export class SportTemplates extends BaseComponent implements OnInit { 

    constructor() { 
     super(); 
    } 

를 대신 다음과 같이 :

@Component({ 
    selector: 'sport-templates', 
    templateUrl: 'templates.component.html', 
    styleUrls: [ 'templates.component.scss' ], 
    encapsulation: ViewEncapsulation.None 
}) 
export class SportTemplates extends BaseComponent implements OnInit { 

    constructor(appConfig: AppConfig) { 
     super(appConfig); 
    } 
+0

@ 각도/코어입니까? – PaladiN

+0

내 질문에 대한 답변을 찾았습니다. https://stackoverflow.com/questions/42461852/angular-2-inject-service-manually Thanks. –

답변

0

없음 당신이 그것을 할 수 없습니다. 주입 서비스은 생성자가 호출 될 때 주입됩니다.

목표는 생성자 서명을 단순화하는 것입니다.

생성자 서명을 단순화 할 필요가 없습니다. 가독성을 위해 여러 줄로 작성할 수 있습니다.

그래서 모든 하위 구성 요소는 귀하의 경우에는 자신의 생성자

에 클래스가 액세스 할 상속 클래스 만 appconfig가를 지정할 필요가 있습니다. 그러나 구성 요소에서 사용되는 하위 구성 요소를 하위 구성 요소라고하면 부모 구성 요소의 변수에 액세스 할 수 없습니다. 당신은 그들을 통과시켜야합니다.

업데이트 귀하의 this.config 항상 상속 된 구성 요소에 표시됩니다. 다시 appConfigSportTemplates 구성 요소에 삽입 할 필요가 없습니다.

+0

답장을 보내 주셔서 감사합니다. 내 질문에 약간의 설명을 추가했습니다. –

+0

@NikolaYankov 업데이트 대답 –

0

이 작업을 수행 할 수 있습니다

myService: MyService = this.injector.get(MyService); 
constructor(private injector:Injector) {} 

인젝터는 생성자 주입을위한 최적의 솔루션을 찾았

+0

그것이 작동하는 동안, 그것은 진정한 방법처럼 보이지 않습니다. 서비스 로케이터 패턴과 비슷합니다. 그 차이는 미묘하다는 것을 인정해야하지만. – XOR