import { Injectable , OnDestroy } from '@angular/core' ; import { Subject } from 'rxjs' ; import { ToastService } from './toast.service' ; export class Message { constructor ( public readonly message ? , public readonly sender ? ) { } } @ Injectable ( { providedIn : 'root' } ) export class MessageService implements OnDestroy { private messageRelay = new Subject < Message > ( ) ; /** Observable to listen for messages */ listen$ = this . messageRelay . asObservable ( ) ; constructor ( private toastService ) { this . listen$ . subscribe ( ( { message , sender } ) => { message = message || '<unspecified message>' ; sender = sender || 'Unknown sender' ; this . toastService . openSnackBar ( message , sender ) ; } ) ; } param message param sender send ( message , sender ? ) ; param message send ( message ) ; send ( message , sender ? ) { if ( message && ! this . messageRelay . closed ) { if ( typeof message === 'string' ) { message = new Message ( message , sender ) ; } this . messageRelay . next ( message ) ; } } ngOnDestroy ( ) { this . messageRelay . complete ( ) ; } }