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(false); private errorSubject = new BehaviorSubject(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!'; } }