【问题标题】:Injecting parent component using class that parent component extends使用父组件扩展的类注入父组件
【发布时间】:2018-10-25 13:39:23
【问题描述】:

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

例如:VegetablesComponents 有一个 BaseListComponent,FruitsComponent 有 BaseListComponent 等等……当然,蔬菜/水果组件内部也有不同的子组件。

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

它会起作用的。

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

【问题讨论】:

    标签: angular components inject


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-18
      相关资源
      最近更新 更多