簡體   English   中英

使用父組件擴展的類注入父組件

[英]Injecting parent component using class that parent component extends

我有多個不同的角度分量。 在這些組件中,還有一個基本列表組件。

例如:VegetablesComponents具有BaseListComponent,FruitsComponent具有BaseListComponent等...當然,Vegetables / Fruits組件內部也有不同的子組件。

BaseListComponent從父組件(VegetablesComponent,FruitsComponent)獲取一些修改某些功能的數據。 這是通過在BaseListComponent上使用@Input()完成的。

因此,我想到了VegetablesComponent,FruitsComponent可以擴展同一類。 而且我可以將父組件注入BaseListComponent內。 可以說:

VegetablesComponents extends HasBaseFunctionality {}

然后在BaseListComponent內部,我將使用構造函數(父級:HasBaseFunctionality,...)。

這將減少BaseList組件上所需的輸入數量,並使它看起來更加整潔。

但是一旦我嘗試這樣做,我就會得到:

StaticInjectorError(AppModule)[ChildComponentComponent -> 
BaseComponentComponent]: 
StaticInjectorError(Platform: core)[ChildComponentComponent -> 
BaseComponentComponent]: 
NullInjectorError: No provider for BaseComponentComponent!

如果我要使用:

constructor(parent: VegetablesComponent) {...}

會的。

因此,我想知道是否有任何方法可以在不使用服務的情況下使用該服務,一旦初始化,我將在該服務上注冊當前基本組件,然后使用服務訪問其值。

您的每個子組件都需要提供父類:

@Component({
    providers: [
        {
            provide: BaseComponentComponent,
            useExisting: VegetablesComponent
       }
   ]
})

然后,您通常可以注入BaseComponentComponent類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM