All files / app/core/toast toast.service.ts

100% Statements 19/19
87.5% Branches 7/8
100% Functions 9/9
100% Lines 13/13

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        36x   36x 36x   36x     26x 26x 26x   26x 7x         1x       1x       1x       12x      
import { Injectable, signal } from '@angular/core';
import { ToastMessage, ToastType } from './toast.interfaces';
 
@Injectable({ providedIn: 'root' })
export class ToastService {
 
  private counter = 0;
  private readonly toastsSignal = signal<ToastMessage[]>([]);
 
  readonly toasts = this.toastsSignal.asReadonly();
 
  show(type: ToastType, message: string, durationMs = 4000): void {
    const id = ++this.counter;
    const toast: ToastMessage = { id, type, message };
    this.toastsSignal.update((current) => [...current, toast]);
 
    setTimeout(() => {
      this.dismiss(id);
    }, durationMs);
  }
 
  success(message: string): void {
    this.show('success', message);
  }
 
  error(message: string): void {
    this.show('error', message);
  }
 
  info(message: string): void {
    this.show('info', message);
  }
 
  dismiss(id: number): void {
    this.toastsSignal.update((current) => current.filter((toast) => toast.id !== id));
  }
}