如何从Angular的子组件中的“top component”获取DI?

问题描述:

From Angular documentation如何从Angular的子组件中的“top component”获取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.

如果我们打开源文件的Hierarchical Dependency Injectors文档,我们可以看到,ACarComponentBCarComponentCCarComponent创建的CarServiceCarService2CarService3三种不同的情况。

但是我如何从父级DI获得CarService子组件BCarComponent如果我还在模块级别提供CarService

+0

_But我怎么能从子组件获取父DI? - 你是什么意思?你的用例是什么?你是否定义了组件或模块的提供者? –

+0

@ AngularInDepth.com,你可以在报价中看到 - 我在“顶部组件”上定义了提供程序,我想从这个角度为内部子组件创建DI。 – ktretyak

+0

是否要跳过所有中间组件注入器?在Suren推荐的模块级别的提供者? –

如果您不会提供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) {} 
} 

在这里,我注入的CarService一个实例为A,B和C汽车部件。在B和C组件中,我没有提供它们自己的CarService(提供程序列表为空),因此它会转到其父组件(在其模板中使用它)并获取相同的实例。

想要服务实例的每个组件首先尝试在它自己的提供程序中找到,如果未找到,则转到上层组件,并尝试在那里找到并等到根组件(此处为upper component是使用它的模板中的当前组件)。如果它没有在那里找到,Angular会抛出一个

Error: No Provider found for YourService

+0

是的,但是我们可以爬到根DI上,但是我们只能爬上“顶部组件”范围吗? – ktretyak

+0

请参阅已编辑的部分。您需要***不给* *你的服务进入该组件的提供商 –

+0

我被编辑了我的问题澄清。据我了解,我不能在CCarComponen如果我在模块级别具有相同的提供者“CarService”,则可以使用“t”级别。 – ktretyak