2017-09-14 6 views
1

From Angular documentation : 우리가 Hierarchical Dependency Injectors의 문서의 소스 파일을 열 경우각도에서 하위 구성 요소의 "상단 구성 요소"에서 DI를 가져 오는 방법은 무엇입니까?

Create a "top component" that acts as the root for all of the module's components. Add the custom HttpBackend provider to the top component's providers list rather than the module's providers. Recall that Angular creates a child injector for each component instance and populates the injector with the component's own providers.

When a child of this component asks for the HttpBackend service, Angular provides the local HttpBackend service, not the version provided in the application root injector. Child components make proper http requests no matter what other modules do to HttpBackend.

Be sure to create module components as children of this module's top component.

, 우리가 ACarComponent, BCarComponentCCarComponentCarService, CarService2CarService3의 세 가지 인스턴스를 생성 것을 볼 수 있습니다.

그러나 모듈 수준에서 CarService을 제공하는 경우 하위 구성 요소의 부모 DI에서 CarService을 어떻게 얻을 수 있습니까? BCarComponent

+0

을 던졌습니다.하지만 부모 컴포넌트를 하위 컴포넌트에서 가져올 수있는 방법은 무엇입니까 - 무슨 뜻입니까? 당신의 유스 케이스는 무엇입니까? 구성 요소 또는 모듈에서 공급자를 정의합니까? –

+0

@ AngularInDepth.com, 견적에서 볼 수 있듯이 "top component"에 대한 공급자를 정의했으며 내부 자식 구성 요소에 대해이 지점에서 DI를 가져 오려고합니다. – ktretyak

+0

모든 중간 구성 요소 인젝터를 건너 뛰고 싶습니까? Suren이 권장하는대로 모듈 수준의 공급자? –

답변

2

제공자를 CCarComponent으로 지정하지 않으면 해당 공급자 인스턴스를 부모 구성 요소에서 가져 오는 등의 작업을 시도합니다.

예를 들어 보겠습니다.

@Component({ 
    selector: 'a-car-comp', 
    template: '<div><b-car-comp></b-car-comp></div>', 
    providers: [CarService] 
}) 
class ACarComponent { 
    constructor(private carService: CarService) {} 
} 


@Component({ 
    selector: 'b-car-comp', 
    template: '<div><c-car-comp></c-car-comp></div>' 
}) 
class BCarComponent { 
    constructor(private carService: CarService) {} 
} 

@Component({ 
    selector: 'c-car-comp', 
    template: '<div></div>' 
}) 
class CCarComponent { 
    constructor(private carService: CarService) {} 
} 

여기서 A, B 및 C 자동차 구성 요소에 CarService의 인스턴스를 주입합니다. B 및 C 구성 요소에서 자신의 CarService (공급자 목록이 비어 있음)을 제공하지 않았으므로 부모 구성 요소 (그의 템플릿에서 사용함)로 이동하여 동일한 인스턴스를 가져옵니다.

서비스의 인스턴스를 원하는 각 구성 요소는 자신의 제공자를 찾지 못하면 상위 구성 요소로 이동하여 거기에서 루트 구성 요소까지 찾으려고 시도합니다 (여기 upper component은 템플릿에있는 현재 구성 요소). 거기도 발견되지 않으면 Angular가

Error: No Provider found for YourService

+0

네, 그렇지만 루트 DI까지 올라갈 수는 있습니다. 그러나 "상단 구성 요소"범위에 대해서만 올라갈 수있는 방법은 무엇입니까? – ktretyak

+0

수정 된 부분보기 *** 제공하지 않아야 함 * * 해당 구성 요소의 공급자에 대한 서비스 –

+0

명확한 설명을 위해 제 질문을 수정했습니다. 이해하는 한, 나는 'CCarComponen'에서 DI를 얻을 수 없습니다. 모듈 수준에서 동일한 공급자 'CarService'를 가지고 있다면 't'수준으로 설정합니다. – ktretyak