2016-06-17 4 views
0

lang.service.ts이라는 서비스를 구축했습니다. 단순히 key: value 메커니즘 일뿐입니다. 내 구성 요소에 필요할 때마다 가져 와서 constructor에 선언 한 다음 {{lang('key').text}}으로 사용합니다. 여태까지는 그런대로 잘됐다.각도 2의 모든 구성 요소에 서비스를로드하는 방법

사실 제가 각 구성 요소에 대해 view-header.component.ts, view-footer.components.ts 및 많은 다른 구성 요소와 같이로드 할 것으로 나타났습니다. Angular 1은 사용하지 않았지만 IIRC는 rootScope.lang(..)과 같은 것을 할 수 있었으며 찾고 있던 것을 성취 할 수있었습니다. Angular 2에서 이와 같은 작업을 수행 할 수있는 방법이 있습니까?

답변

1

루트 구성 요소에 서비스를 등록하면 모든 하위 구성 요소가 서비스에 액세스 할 수 있습니다. 루트 구성 요소에

... 당신의 아이 컴퍼넌트에

import { Component } from '@angular/core'; 

import { YourService } from './my-servive.service.ts'; 
import { ChildComponent } from './child-component.component.ts'; 

@Component({ 
    selector: 'root-component', 
    providers: [YourService], 
    directives: [ChildComponent], 
    template: `<child-component></child-component>` 
}) 
export class RootComponent {} 

...

import { Component } from '@angular/core'; 
import { YourService } from './my-servive.service.ts'; 

@Component({ 
    selector: 'child-component' 
}) 
export class ChildComponent { 
    contructor(private myService: YourService) {} 
} 

희망이 당신을 도울.

관련 문제