Files
frontend/src/app/loading.service.ts
Piet Ostendorp 5addba879a Add error handling and snackbar notifications
Introduces error state management in LoadingService, displays error bar and snackbar notifications in the UI, and updates ScheduleComponent to use the new error handling. Also adds custom theming for error snackbar and progress bar.
2025-10-31 16:19:02 +01:00

81 lines
2.1 KiB
TypeScript

import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoadingService {
private loadingSubject = new BehaviorSubject<boolean>(false);
private errorSubject = new BehaviorSubject<boolean>(false);
public loading$ = this.loadingSubject.asObservable();
public error$ = this.errorSubject.asObservable();
constructor(private snackBar: MatSnackBar) {}
show(): void {
this.loadingSubject.next(true);
this.errorSubject.next(false);
}
hide(): void {
this.loadingSubject.next(false);
this.errorSubject.next(false);
}
showError(messageOrError?: string | HttpErrorResponse | any): void {
this.loadingSubject.next(false);
this.errorSubject.next(true);
if (!messageOrError) {
return;
}
const message = this.getErrorMessage(messageOrError);
const snackBarRef = this.snackBar.open(message, 'Schließen', {
duration: 0,
panelClass: ['error-snackbar'],
horizontalPosition: 'center',
verticalPosition: 'bottom'
});
snackBarRef.afterDismissed().subscribe(() => {
this.hide();
});
}
private getErrorMessage(error?: string | HttpErrorResponse | any): string {
if (typeof error === 'string') {
return error;
}
if (error instanceof HttpErrorResponse) {
if (error.status === 0) {
return 'Netzwerkfehler: Keine Verbindung zum Server möglich!';
}
if (error.status >= 500) {
return `Serverfehler (${error.status}): ${error.statusText || 'Interner Serverfehler'}`;
}
if (error.status >= 400) {
const errorMessage = error.error?.message || error.error?.error || error.statusText;
return `Fehler (${error.status}): ${errorMessage}`;
}
return `HTTP Fehler (${error.status}): ${error.statusText}`;
}
if (error.message) {
return error.message;
}
return 'Ein unbekannter Fehler ist aufgetreten!';
}
}