小编Neu*_*der的帖子

如何捕获显示Angular动态组件时发生的错误?

我有一个显示通知的组件。它有一个ViewChild具有一个ViewContainerRef

根据通知的类型,我显示不同的组件来代替该viewChild。这是基于通知类型创建和添加组件的代码:

private loadInappNotificationItem(messageType: MessageType): void {
  const inappNotificationItemComponent: Type<IInappNotificationItemComponent>
    = this.inappNotificationItemMapping.get(messageType);
  if (inappNotificationItemComponent === undefined) {
    this.hasCustomComponent = false;
    return;
  }

  const componentFactory: ComponentFactory<IInappNotificationItemComponent> =
    this.componentFactoryResolver.resolveComponentFactory(inappNotificationItemComponent);

  this.hasCustomComponent = true;
  const viewContainerRef: ViewContainerRef = this.inappNotificationItemHost.viewContainerRef;
  viewContainerRef.clear();

  const componentRef: ComponentRef<IInappNotificationItemComponent> =
    viewContainerRef.createComponent(componentFactory);

  const component: IInappNotificationItemComponent = componentRef.instance;
  component.notification = this.notification;
}
Run Code Online (Sandbox Code Playgroud)

这可以按预期工作,但是现在我想显示一个备用组件,如果在显示通知组件时出现任何问题(例如,当notification属性的结构错误时)。

为此,我需要能够在某个地方注册一个函数,该函数在由于某些原因显示viewChild失败时会调用该函数,以便我可以删除它并显示后备。

我知道我可以在包含该组件的模块上注册自定义ErrorHandler,并且可以捕获我想捕获的错误,但是在该处理程序中,我没有引用其viewChild无法显示的通知组件。

更新:

我能够编写一个类装饰器,以捕获组件类的每个方法中的每个错误,这又使我能够在组件类中的任何内容引发错误时显示回退。当然,我需要以此来装饰所有自定义组件,但是没关系,只要我只需要添加一个装饰器即可。(请参阅我的部分回答

但是,这对于源自模板的错误没有帮助!例如,访问自定义组件模板中的属性时,该属性不存在。因此,另一个可能有助于解决此问题的问题是: 如何在我的组件中捕获运行时模板错误(而不是全局或模块级别,因为我在那里没有引用损坏的组件)

angular

6
推荐指数
1
解决办法
251
查看次数

标签 统计

angular ×1