I am trying to implement a general http handler error, but I found a strager behavior. My Error component only update the message error only after second click, but I dont know why.
The code is available here in StackBlitz: enter link description here
In app.component.ts on click I try a http request and it will fail, just to throw an error.
onClick() {
this.http
.get('http://localhost:8080/test')
.pipe(catchError(this.errorHandler))
.subscribe(() => {});
}
errorHandler(error: HttpErrorResponse) {
return throwError(error.message);
}
All errors are handled in global.error.ts and each error is add in error.service.ts:
export class GlobalErrorHandler implements ErrorHandler {
constructor(private errorService: ErrorService) {}
handleError(error: Error) {
this.errorService.add('New Error');
}
}
The error.service.ts uses BehaviorSubject and notify my error.component.ts:
export class ErrorService {
public notification = new BehaviorSubject<string>('Initial Value');
add(err: string) {
this.notification.next(err);
}
}
Finally, the error.component.ts must update the message error on screen, but it works only in the second click, but the console.log works perfect.
export class ErrorComponent implements OnInit {
public errorMessage: string = '';
constructor(public errorService: ErrorService) {}
ngOnInit() {
this.errorService.notification.subscribe({
next: (notification) => {
console.log('Error Component');
this.errorMessage = notification;
},
});
}
}
Questions:
- Any reason for this behavior?
- Any suggestions for implementing a Global Handler Http Error?