简体   繁体   English

Angular4:在构造函数中注入父组件 - 使其失败安全

[英]Angular4: Injecting parent component in the constructor - making it fails safe

Somewhere on the web I saw a tutorial about creating a tab component in it used this awesomely simple pattern 在网络的某个地方,我看到了一个关于在其中创建选项卡组件的教程,使用了这个非常简单的模式

// TABS COMPONENT // TABS COMPONENT

export class TabsComponent{
    tabs: TabItemComponent[];

    addTab(tab: TabItemComponent){
        this.tabs.push(tab);
    }
}

// TAB ITEM COMPONENT // TAB项目组件

export class TabItemComponent{
    constructor(private tabsComponent: TabsComponent){
        this.tabsComponent.addTab(this);
    }
}

// VIEW //查看

<tabs>
    <tab-item>text 1</tab-item>
    <tab-item>Text 2</tab-item>
</tabs>

Really cool and clean pattern to get the parent injected into the child 非常凉爽和干净的模式,让父母注入孩子

now, this works fine when the parent is actually there in the view... so perfect for tabs... 现在,当父视图在视图中实际存在时,这可以正常工作...非常适合制表符...

a little less perfect for ButtonGroupComponent and ButtonComponent scenario, where Button can be standalone and not necessarily wrapped in the Button Group 对ButtonGroupComponent和ButtonComponent场景来说不太完美,其中Button可以是独立的,不一定包含在Button Group中

I have similar pattern there with an exception 我有类似的模式有一个例外

constructor(private buttonGroup: ButtonGroupComponent) {
  if (this.buttonGroup) {
    this.buttonGroup.addButton(this);
  }
}

But, if the button is standalone this does not work, I get an error: 但是,如果按钮是独立的,这不起作用,我收到一个错误:

ERROR Error: Uncaught (in promise): Error: No provider for ButtonGroupComponent! 错误错误:未捕获(承诺):错误:没有ButtonGroupComponent的提供程序!

Any ideas how to prevent the error in the constructor? 任何想法如何防止构造函数中的错误?

You can decorate the argument with @Optional() . 您可以使用@Optional()修饰参数。 See the documentation . 请参阅文档

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

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