komponents erstellen
This commit is contained in:
55
src/app/shared/services/snackbar.service.ts
Normal file
55
src/app/shared/services/snackbar.service.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { BehaviorSubject, Observable } from 'rxjs';
|
||||
|
||||
// Exportiere das Interface, damit es wiederverwendbar ist
|
||||
export interface Snackbar {
|
||||
id: number;
|
||||
message: string;
|
||||
state: 'visible' | 'fading';
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class SnackbarService {
|
||||
// BehaviorSubject hält den aktuellen Zustand und benachrichtigt alle "Zuhörer"
|
||||
private snackbarsSubject = new BehaviorSubject<Snackbar[]>([]);
|
||||
snackbars$: Observable<Snackbar[]> = this.snackbarsSubject.asObservable();
|
||||
|
||||
// Die Position wird ebenfalls hier als globaler Zustand verwaltet
|
||||
private positionSubject = new BehaviorSubject<'top' | 'bottom'>('top');
|
||||
position$: Observable<'top' | 'bottom'> = this.positionSubject.asObservable();
|
||||
|
||||
private nextId = 0;
|
||||
|
||||
// Öffentliche Methode zum Anzeigen einer Snackbar
|
||||
show(message: string): void {
|
||||
const newSnackbar: Snackbar = { id: this.nextId++, message, state: 'visible' };
|
||||
const currentSnackbars = [newSnackbar, ...this.snackbarsSubject.value];
|
||||
this.snackbarsSubject.next(currentSnackbars);
|
||||
|
||||
// Timer zum automatischen Schließen
|
||||
setTimeout(() => this.close(newSnackbar.id), 5000);
|
||||
}
|
||||
|
||||
// Öffentliche Methode zum Schließen einer Snackbar
|
||||
close(id: number): void {
|
||||
let currentSnackbars = this.snackbarsSubject.value;
|
||||
const index = currentSnackbars.findIndex(s => s.id === id);
|
||||
|
||||
if (index > -1 && currentSnackbars[index].state === 'visible') {
|
||||
currentSnackbars[index].state = 'fading';
|
||||
this.snackbarsSubject.next([...currentSnackbars]);
|
||||
|
||||
setTimeout(() => {
|
||||
currentSnackbars = this.snackbarsSubject.value.filter(s => s.id !== id);
|
||||
this.snackbarsSubject.next(currentSnackbars);
|
||||
}, 100); // Muss zur CSS-Dauer passen
|
||||
}
|
||||
}
|
||||
|
||||
// Öffentliche Methode zum Ändern der Position
|
||||
setPosition(position: 'top' | 'bottom'): void {
|
||||
this.positionSubject.next(position);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user