I'm trying to do the following in Angular 2 (typescript): For each error (especially errors from the backend server) - present the error to the user (in the UI) - in the main component (mainly since I do't want to write same code in each component).
Is it a simple way to do it? I guess what I need is a way to set an "error" member in the main component? How do I do it if I override ExceptionHandler?
thanx, Pavel.
Create NotificationService in shared directory
import { Injectable } from '@angular/core';
import { Message } from 'primeng/primeng';
@Injectable()
export class NotificationService {
message: Message[];
constructor() {
this.message = [];
}
success(detail: string, summary?: string): void {
this.message.push({
severity: 'success', summary: summary, detail: detail
});
}
info(detail: string, summary?: string): void {
this.message.push({
severity: 'info', summary: summary, detail: detail
});
}
warning(detail: string, summary?: string): void {
this.message.push({
severity: 'warn', summary: summary, detail: detail
});
}
error(detail: string, summary?: string): void {
this.message.push({
severity: 'error', summary: summary, detail: detail
});
}
}
create a custom ExceptionHandler (ErrorHandler in RC 6) in shared directory
import { ErrorHandler, Inject } from '@angular/core';
import { NotificationService } from './notification.service';
export class CustomErrorHandler implements ErrorHandler {
constructor(@Inject(NotificationService) private notificationService: NotificationService) {
}
handleError(error: any): void {
this.showErrorInConsole(error);
setTimeout(() =>
this.notificationService.error(error.json().Message), 1);
}
private showErrorInConsole(error: any) :void {
if (console && console.group && console.error) {
console.group("Error Log");
console.error(error);
console.error(error.message);
console.error(error.stack);
console.groupEnd();
}
}
}
update AppModule for overriding default error handler
import { GrowlModule } from 'primeng/primeng';
...
import { NotificationService } from './shared/notification.service';
import { CustomErrorHandler } from './shared/custom-error-handler';
@NgModule({
imports: [
...,
GrowlModule // prime ng notification
],
declarations: [
...
],
providers: [
...,
NotificationService, // added
{ provide: ErrorHandler, useClass: CustomErrorHandler } // overrride default error handler
],
bootstrap: [AppComponent]
})
export class AppModule { }
finally in AppComponent:
import { Component } from '@angular/core';
import { Message } from 'primeng/primeng';
import { NotificationService } from './shared/notification.service';
@Component({
selector: 'my-app',
template: `
<p-growl [value]="getMessages()"></p-growl>
`
})
export class AppComponent{
constructor(private notification: NotificationService) {
}
getMessages(): Message[] {
return this.notification.message;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With