All files / app/services notification.service.ts

100% Statements 9/9
100% Branches 4/4
100% Functions 7/7
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90                                1x 25x 25x               21x             3x                         2x                         2x                         1x                         8x        
import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';
 
export type NotificationType = 'success' | 'error' | 'info' | 'warning';
 
export interface Notification {
  id: number;
  type: NotificationType;
  message: string;
  title?: string;
  duration?: number; // Durée en millisecondes (0 = ne se ferme pas automatiquement)
}
 
@Injectable({
  providedIn: 'root'
})
export class NotificationService {
  private notifications$ = new Subject<Notification>();
  private notificationId = 0;
 
  constructor() {}
 
  /**
   * Observable pour écouter les nouvelles notifications
   */
  getNotifications(): Observable<Notification> {
    return this.notifications$.asObservable();
  }
 
  /**
   * Afficher une notification de succès
   */
  success(message: string, title?: string, duration: number = 3000): void {
    this.show({
      id: ++this.notificationId,
      type: 'success',
      message,
      title,
      duration
    });
  }
 
  /**
   * Afficher une notification d'erreur
   */
  error(message: string, title?: string, duration: number = 5000): void {
    this.show({
      id: ++this.notificationId,
      type: 'error',
      message,
      title,
      duration
    });
  }
 
  /**
   * Afficher une notification d'information
   */
  info(message: string, title?: string, duration: number = 3000): void {
    this.show({
      id: ++this.notificationId,
      type: 'info',
      message,
      title,
      duration
    });
  }
 
  /**
   * Afficher une notification d'avertissement
   */
  warning(message: string, title?: string, duration: number = 4000): void {
    this.show({
      id: ++this.notificationId,
      type: 'warning',
      message,
      title,
      duration
    });
  }
 
  /**
   * Afficher une notification personnalisée
   */
  private show(notification: Notification): void {
    this.notifications$.next(notification);
  }
}