import { Component , HostListener , OnInit } from '@angular/core' ; import { MultiWindowService , Message , KnownAppWindow } from 'ngx-multi-window' ; import { NameGeneratorService } from './providers/name-generator.service' ; @ Component ( { selector : 'app-root' , templateUrl : './app.component.html' , styleUrls : [ './app.component.css' ] , } ) export class AppComponent implements OnInit { ownName : string ; ownId : string ; windows : KnownAppWindow [ ] = [ ] ; logs : string [ ] = [ ] ; newName : string ; @ HostListener ( 'window:unload' ) unloadHandler ( ) { this . multiWindowService . saveWindow ( ) ; } constructor ( private multiWindowService , private nameGenerator ) { } ngOnInit ( ) { this . ownId = this . multiWindowService . id ; this . ownName = this . multiWindowService . name ; if ( this . ownName . indexOf ( this . ownId ) >= 0 ) { this . multiWindowService . name = this . ownName = this . nameGenerator . getRandomFakeName ( ) ; } this . newName = this . ownName ; this . windows = this . multiWindowService . getKnownWindows ( ) ; this . multiWindowService . onMessage ( ) . subscribe ( ( value ) => { this . logs . unshift ( 'Received a message from ' + value . senderId + ': ' + value . data ) ; } ) ; this . multiWindowService . onWindows ( ) . subscribe ( knownWindows => this . windows = knownWindows ) ; } public sendMessage ( recipientId , message ) { if ( recipientId === this . ownId ) { this . logs . unshift ( 'Can\'t send messages to itself. Select another window.' ) ; return ; } this . multiWindowService . sendMessage ( recipientId , 'customEvent' , message ) . subscribe ( ( messageId ) => { this . logs . unshift ( 'Message send, ID is ' + messageId ) ; } , ( error ) => { this . logs . unshift ( 'Message sending failed, error: ' + error ) ; } , ( ) => { this . logs . unshift ( 'Message successfully delivered' ) ; } ) ; } public removeLogMessage ( index ) { this . logs . splice ( index , 1 ) ; } public changeName ( ) { this . multiWindowService . name = this . ownName = this . newName ; } public newWindow ( ) { const newWindowData = this . multiWindowService . newWindow ( ) ; newWindowData . created . subscribe ( ( ) => { } , ( err ) => { this . logs . unshift ( 'An error occured while waiting for the new window to start consuming messages' ) ; } , ( ) => { this . logs . unshift ( 'The new window with id ' + newWindowData . windowId + ' got created and starts consuming messages' ) ; } ) ; window . open ( '?' + newWindowData . urlString ) ; } public windowTrackerFunc ( item , index ) { return item . id ; } }