import { Injectable } from '@angular/core'; @Injectable() export class DialogService { private modals: any[] = []; constructor() { } add(modal: any) { this.validation(modal.dialogId).isDuplicate(); this.validation(modal.dialogId).isNotEmpty(); this.modals.push(modal); } remove(modal: any) { this.modals.splice(this.fetchIndex(modal.dialogId), 1); } open(modalId: string, data?: any) { this.modals[this.validation(modalId).isDefined()].open(data); } close(modalId: string, data?: any) { this.modals[this.validation(modalId).isDefined()].close(data); } onDialogOpen(modalId: string, subscriber: any) { if (typeof window !== 'undefined') { setTimeout(() => { this.modals[this.validation(modalId).isDefined()].afterOpen$.subscribe(subscriber); }, 0); } } onDialogClose(modalId: string, subscriber: any) { if (typeof window !== 'undefined') { setTimeout(() => { this.modals[this.validation(modalId).isDefined()].afterClose$.subscribe(subscriber); }, 0); } } validation(modalId: string) { const modalIndex = this.fetchIndex(modalId); return { isNotEmpty: () => { if (modalId && modalId.length > 0) { return modalIndex; } else { throw new Error('Id for must be set and non-empty'); } }, isDefined: () => { if (modalIndex !== -1) { return modalIndex; } else { throw new Error(` with id '${modalId}' was not found`); } }, isDuplicate: () => { if (modalIndex !== -1) { throw new Error(`id '${modalId}' for is already set!`); } } }; } fetchIndex(modalId: string) { const modalIndex = this.modals.findIndex(modal => modal.dialogId === modalId); return modalIndex; } }