首页 > 解决方案 > 使用父组件扩展的类注入父组件

问题描述

我有多个不同的角度分量。在许多这些组件中还有一个基本列表组件。

举个例子:VegetablesComponents 有一个 BaseListComponent,FruitsComponent 有 BaseListComponent 等等……当然,在 Vegetables/Fruits 组件中也有不同的子组件。

BaseListComponent 从父组件(VegetablesComponent、FruitsComponent)获取一些修改某些功能的数据。这是使用 BaseListComponent 上的 @Input() 完成的。

所以我想到了蔬菜组件,水果组件可以扩展同一个类。我可以在 BaseListComponent 中注入父组件。让我们说:

VegetablesComponents extends HasBaseFunctionality {}

然后在 BaseListComponent 中,我将使用构造函数(父级:HasBaseFunctionality,...)。

这将减少 BaseList 组件所需的输入数量,并使其看起来更干净。

但是一旦我尝试这样做,我得到了:

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

如果我会使用:

constructor(parent: VegetablesComponent) {...}

它会起作用的。

所以我想知道是否有任何方法可以在不使用服务的情况下执行此操作,一旦初始化,我将在该服务上注册当前的基本组件,然后使用服务访问它的值。

标签: angularcomponentsinject

解决方案


您的每个子组件都需要提供父类:

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

然后就可以正常注入BaseComponentComponent类型了。


推荐阅读