import { Component } from "@angular/core"; import { NotificationService } from "../../services/notification.service"; export interface NotificationElement { message: string; type: "info" | "danger" | "warn" | "success"; timeout: number | undefined; } interface NotificationItem { element: NotificationElement; shownAt: Date; } @Component({ selector: "app-notification-bar", templateUrl: "./notification-bar.component.html", styleUrls: ["./notification-bar.component.scss"], }) export class NotificationBarComponent { items: NotificationItem[] = []; isRunning: boolean; constructor(private notificationService: NotificationService) { this.isRunning = false; this.notificationService.notification$.subscribe((notification) => { if (notification !== undefined) { this.items.push({ element: notification, shownAt: new Date(), }); this.startTimeoutIfNecessary(); } }); } startTimeoutIfNecessary(): void { if (this.isRunning === true) { return; } let intervalId = setInterval(() => { this.isRunning = true; let now = new Date(); this.items.forEach((item) => { if (item.element.timeout !== undefined) { let timeout = new Date( item.shownAt.getTime() + item.element.timeout * 1000 ); if (timeout < now) { this.dismiss(item); } } }); if (this.items.length === 0) { clearInterval(intervalId); this.isRunning = false; } }, 1000); } dismiss(item: NotificationItem): void { this.items = this.items.filter((i) => i !== item); } }