【问题标题】:using same component with different state as child in multiple components angular 6/7在多个组件中使用具有不同状态的相同组件作为子组件角度 6/7
【发布时间】:2019-05-16 09:29:57
【问题描述】:

我有一个 ErrorComponent,我将它添加到我的两个组件中。 1 是父母,其他是它的孩子。问题是两个组件中的错误组件采用相同的实例。因此,每当我只想在父组件中显示错误时,它也会显示在子组件上,反之亦然。

我想将两个错误组件保留为不同的实例。请帮忙。提前致谢。

你可以在这里玩代码https://stackblitz.com/edit/angular-21woxg?file=src%2Findex.html

【问题讨论】:

标签: angular components angular6 angular-components angular7


【解决方案1】:

您可以做的是向您的组件提供您希望它们动态的东西作为输入,然后您将能够为您的错误组件设置不同的状态,例如,如果您想自定义错误消息你的error-component.ts你加:

export class ErrorComponent  {
  @Input()ErrorMessage='default error'
}

然后在你的parent-component.html

<my-error-component [ErrorMessage]="http failure .."> </my-error-component>

在你的child-component.html

<my-error-component [ErrorMessage]="No internet connection .."> </my-error-component>

【讨论】:

  • 应该从 HttpInterceptor 添加错误消息,我不想按照您的建议在每个组件级别编写消息。
  • 您当前的实现不提供在您的Error component 直接订阅您的notify service 的每个错误组件中显示不同错误消息的灵活性,每次httpInterceptor 以这种方式拦截错误时都会发出HTTP 错误将直接显示在您的错误组件中
【解决方案2】:

您目前所拥有的那种实现方式是不可能的。原因是,您在ParentComponentChildComponent 的模板中都使用了ErrorComponent。而且您没有任何逻辑可以有条件地在ParentComponentChildComponent 的模板中显示ErrorComponent

话虽如此,要完成这项工作,您必须执行以下操作:

  1. 从您的拦截器服务中,发送一个字段来确定错误消息需要显示的位置(示例中为showOn
  2. 使ErrorComponent 成为一个哑组件。让它接受errors 作为@Input
  3. 在您的ParentComponentChildComponent 中注入NotifyService 作为依赖项并订阅errorNotifications。由于我们从拦截器服务中设置showOn 属性,这两个订阅将收到的错误对象也将具有此showOn 属性。
  4. 基于此,您可以在ParentComponentChildComponent 上设置displayError 属性。然后,您也可以将其用于*ngIf,以有条件地显示ErrorComponent

这里有一个Working Sample StackBlitz 供您参考。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2020-09-13
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 2019-07-04
    • 2023-01-18
    相关资源
    最近更新 更多