import { Injectable } from '@angular/core' ; export type EventHandler = ( ... args : any [ ] ) => any ; @ Injectable ( { providedIn : 'root' , } ) export class Events { private c = new Map < string , EventHandler [ ] > ( ) ; constructor ( ) { } param topic param handler subscribe ( topic , ... handlers ) { let topics = this . c . get ( topic ) ; if ( ! topics ) { this . c . set ( topic , topics = [ ] ) ; } topics . push ( ... handlers ) ; } param topic param handler return unsubscribe ( topic , handler ? ) { if ( ! handler ) { return this . c . delete ( topic ) ; } const topics = this . c . get ( topic ) ; if ( ! topics ) { return false ; } const index = topics . indexOf ( handler ) ; if ( index < 0 ) { return false ; } topics . splice ( index , 1 ) ; if ( topics . length === 0 ) { this . c . delete ( topic ) ; } return true ; } param topic param eventData publish ( topic , ... args ) { const topics = this . c . get ( topic ) ; if ( ! topics ) { return null ; } return topics . map ( handler => { try { return handler ( ... args ) ; } catch ( e ) { console . error ( e ) ; return null ; } } ) ; } }