简体   繁体   English

使用父组件扩展的类注入父组件

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

I have multiple different angular components. 我有多个不同的角度分量。 Also there is a base list component in lots of these components. 在这些组件中,还有一个基本列表组件。

For an example: VegetablesComponents has a BaseListComponent, FruitsComponent has BaseListComponent etc... Ofcourse there are different child components inside Vegetables/Fruits components as well. 例如:VegetablesComponents具有BaseListComponent,FruitsComponent具有BaseListComponent等...当然,Vegetables / Fruits组件内部也有不同的子组件。

BaseListComponent gets some data that modifies some functionalities from parent component (VegetablesComponent, FruitsComponent). BaseListComponent从父组件(VegetablesComponent,FruitsComponent)获取一些修改某些功能的数据。 This was done using @Input() on BaseListComponent. 这是通过在BaseListComponent上使用@Input()完成的。

So I got the idea that VegetablesComponent, FruitsComponent could extends same Class. 因此,我想到了VegetablesComponent,FruitsComponent可以扩展同一类。 And I could inject parent component inside BaseListComponent. 而且我可以将父组件注入BaseListComponent内。 Lets say: 可以说:

VegetablesComponents extends HasBaseFunctionality {}

And then inside BaseListComponent I would use constructor(parent: HasBaseFunctionality,...). 然后在BaseListComponent内部,我将使用构造函数(父级:HasBaseFunctionality,...)。

This would reduce the numbers of inputs that would be needed on the BaseList component and it would make it look a lot cleaner. 这将减少BaseList组件上所需的输入数量,并使它看起来更加整洁。

But once I tried to do this I got the: 但是一旦我尝试这样做,我就会得到:

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

If I would use: 如果我要使用:

constructor(parent: VegetablesComponent) {...}

It would work. 会的。

So I was wondering if there was any way of doing this without using a service on which I would register the current base component once initializes and then access its values using service. 因此,我想知道是否有任何方法可以在不使用服务的情况下使用该服务,一旦初始化,我将在该服务上注册当前基本组件,然后使用服务访问其值。

Each of your child components needs to provide the parent class: 您的每个子组件都需要提供父类:

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

Then you can normally inject BaseComponentComponent type. 然后,您通常可以注入BaseComponentComponent类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM