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文檔,我們可以看到,ACarComponent
,BCarComponent
和CCarComponent
創建的CarService
,CarService2
和CarService3
三種不同的情況。
但是我如何從父級DI獲得CarService
子組件BCarComponent
如果我還在模塊級別提供CarService
?
_But我怎麼能從子組件獲取父DI? - 你是什麼意思?你的用例是什麼?你是否定義了組件或模塊的提供者? –
@ AngularInDepth.com,你可以在報價中看到 - 我在「頂部組件」上定義了提供程序,我想從這個角度爲內部子組件創建DI。 – ktretyak
是否要跳過所有中間組件注入器?在Suren推薦的模塊級別的提供者? –