Angular 在角度页面中显示全局错误消息
我在父页面组件中嵌套了子组件。目前,我有一个事件发射器,它向父组件发出错误事件和消息,以便在遇到错误时显示。是否有一种方法可以冒泡错误消息,使其显示在所有页面上。我正在考虑使用appcomponent文件,但不确定如何使用它Angular 在角度页面中显示全局错误消息,angular,Angular,我在父页面组件中嵌套了子组件。目前,我有一个事件发射器,它向父组件发出错误事件和消息,以便在遇到错误时显示。是否有一种方法可以冒泡错误消息,使其显示在所有页面上。我正在考虑使用appcomponent文件,但不确定如何使用它 Child: @Output() errorEmitter = new EventEmitter(); errorEmission(message: string){ this.errorEmitter.emit(message); } Parent: &l
Child:
@Output() errorEmitter = new EventEmitter();
errorEmission(message: string){
this.errorEmitter.emit(message);
}
Parent:
<app-manage (errorEmitter)='displayError($event)'></app-manage>
displayError(message: string) {
this.errorMessageIsOn = true;
this.errorMessageString = message;
}
Child:
@Output()errorEmitter=新的EventEmitter();
errorEmission(消息:字符串){
this.errorEmitter.emit(消息);
}
起源:
显示错误(消息:字符串){
this.errorMessageIsOn=true;
this.errorMessageString=消息;
}
有没有一种方法可以使其可扩展,这样我就不必为每个页面而只是每个组件重写此代码?简单地说,这一想法是将错误与UI逻辑完全解耦:
通知.service.ts
:
从'@angular/core'导入{Injectable}
从'rxjs'导入{BehaviorSubject,Subject};
@注射的({
providedIn:'根'
})
出口类通知服务{
私有只读错误对象$=新主题();
公共错误$(){
返回此.ErrorsObject$.asObservable();
}
公共淋浴ROR(消息:字符串):无效{
this.ErrorsObject$.next(消息);
}
}
示例notification.component.ts
,应用程序中应该只有一个实例
从“@angular/core”导入{Component,Input}”;
从“/notification.service”导入{NotificationService};
@组成部分({
选择器:“通知”,
模板:`
你好{{error}}!
`,
风格:[
`
h1{
字体系列:Lato;
}
`
]
})
导出类NotificationComponent{
错误$=此.notificationService.errors$();
构造函数(私有只读notificationService:notificationService){}
}
这也是一个可以发送消息的示例组件,可以是任何其他执行此操作的组件
从“@angular/core”导入{Component,Input}”;
从“/notification.service”导入{NotificationService};
@组成部分({
选择器:“你好”,
模板:`
显示错误
`,
风格:[
`
钮扣{
字体系列:Lato;
}
`
]
})
导出类HelloComponent{
@Input()名称:string;
构造函数(私有只读notificationService:notificationService){}
onClick():void{
此为.notificationService.bathror(
`此错误已在${Date.now()上发布`
);
}
}
所以,现在只要您在任何组件中注入通知服务并通过该服务发送消息,通知组件就能够订阅它并全局显示它们。这是一个证明它有效的例子
显然,这是非常简单的,您需要实现更多,但这应该让您走上正确的轨道
一个改进是从通知服务中删除可观察的错误$
,只允许通知组件访问它。您可以通过实现一个内部通知服务来实现这一点,该服务将充当通知服务和通知组件之间的桥梁。你赢了什么?通知服务不再公开可观察的错误$
,只公开发送消息的方法
notification.service.ts
从“@angular/core”导入{Injectable};
从“rxjs”导入{Subject};
从“/notification internal.service”导入{NotificationInternalService}”;
@注射的({
提供于:“根”
})
出口类通知服务{
构造函数(私有只读内部服务:NotificationInternalService){}
公共淋浴ROR(消息:字符串):无效{
this.internalService.errorSubject$.next(消息);
}
}
notification internal.service.ts
从“@angular/core”导入{Injectable};
从“rxjs”导入{Subject};
@注射的({
提供于:“根”
})
导出类通知内部服务{
public errorSubject$=新主题();
公共获取错误$(){
返回此.errorSubject$.asObservable();
}
}
和notification.component.ts
现在引用notification internal.service.ts
从“@angular/core”导入{Component,Input}”;
从“/notification internal.service”导入{NotificationInternalService}”;
@组成部分({
选择器:“通知”,
模板:`
你好{{error}}!
`,
风格:[
`
h1{
字体系列:Lato;
}
`
]
})
导出类NotificationComponent{
错误$=this.service.error$;
构造函数(私有只读服务:NotificationInternalService){}
}
也许可以使用服务将消息共享给所有组件或ngrxa weel done简单通知组件Thank@malbarmawi Thank you@EvaldasBuinauskas非常有用-感谢您花时间发布此解决方案