我有一个显示通知的组件。它有一个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无法显示的通知组件。
更新:
我能够编写一个类装饰器,以捕获组件类的每个方法中的每个错误,这又使我能够在组件类中的任何内容引发错误时显示回退。当然,我需要以此来装饰所有自定义组件,但是没关系,只要我只需要添加一个装饰器即可。(请参阅我的部分回答)
但是,这对于源自模板的错误没有帮助!例如,访问自定义组件模板中的属性时,该属性不存在。因此,另一个可能有助于解决此问题的问题是: 如何在我的组件中捕获运行时模板错误(而不是全局或模块级别,因为我在那里没有引用损坏的组件)
@Neutrosider如果您引用应用程序代码生成的随机js错误,我会做的是将这些组件中的角度钩子包装到 try {} catch 语句中,但这看起来不太好。或者创建一些打字稿自定义注释,其行为如下
interface ErrorHandledComponent {
isInErrorState: boolean;
}
export function HandleComponentErrors() {
return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const oriiginalHook = target[propertyKey].bind(target);
target[propertyKey] = (...args) => {
try {
oriiginalHook(...args)
} catch (e) {
if (isDevMode) {
console.error(e);
}
target.isInErrorState = true;
}
}
}
}
@Component({
....
template: `<ng-container *ngIf="!isInErrorState">...content<ng-container>
<ng-container *ngIf="isInErrorState">...error content<ng-container>`
})
export class CumponentWithErrorHandling implements {
isInErrorState: boolean;
@HandleComponentErrors()
ngOnInit() {
...your custom code
}
}
Run Code Online (Sandbox Code Playgroud)
基本上注释所有角度钩子,如果这就是您想要实现的目标,那么您将在代码实现中对 js 错误进行良好的渲染,或者可能进一步分派错误或将其记录到后端。我希望它有帮助
| 归档时间: |
|
| 查看次数: |
251 次 |
| 最近记录: |