2017-09-14 114 views
1

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推薦的模塊級別的提供者? –

回答

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) {} 
} 

在這裏,我注入的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

相關問題