notification.service.ts (1429B)
1 import { Injectable, signal } from '@angular/core'; 2 3 export type NotificationType = 'primary' | 'secondary' | 'success' | 'danger' | 'warning' | 'info' | 'light' | 'dark'; 4 5 export interface Notification { 6 id: number; 7 message: string; 8 type: NotificationType; 9 } 10 11 @Injectable({ 12 providedIn: 'root' 13 }) 14 export class NotificationService { 15 private notificationIdCounter = 0; 16 private notifications = signal<Notification[]>([]); 17 18 // Expose as readonly signal 19 readonly notifications$ = this.notifications.asReadonly(); 20 21 /** 22 * Show a notification that auto-dismisses after 3 seconds 23 * @param message The message to display 24 * @param type The alert type (default: 'info') 25 */ 26 show(message: string, type: NotificationType = 'info'): void { 27 const id = ++this.notificationIdCounter; 28 const notification: Notification = { id, message, type }; 29 30 // Add notification to the list 31 this.notifications.update(notifications => [...notifications, notification]); 32 33 // Auto-dismiss after 3 seconds 34 setTimeout(() => { 35 this.dismiss(id); 36 }, 3000); 37 } 38 39 /** 40 * Manually dismiss a notification by ID 41 * @param id The notification ID to dismiss 42 */ 43 dismiss(id: number): void { 44 this.notifications.update(notifications => 45 notifications.filter(n => n.id !== id) 46 ); 47 } 48 49 /** 50 * Clear all notifications 51 */ 52 clearAll(): void { 53 this.notifications.set([]); 54 } 55 }