import { Injectable , EventEmitter , Inject } from '@angular/core' ; import { Observable } from 'rxjs/Observable' ; import 'rxjs/add/operator/share' ; import * as io from 'socket.io-client' ; import { SocketIoConfig } from './socketIoConfig' ; import { SOCKET_CONFIG_TOKEN } from './socket-io.module' ; export class WrappedSocket { subscribersCounter = 0 ; ioSocket : any ; constructor ( @ Inject ( SOCKET_CONFIG_TOKEN ) config ) { const url = config . url || '' ; const options = config . options || { } ; this . ioSocket = io ( url , options ) ; } on ( eventName , callback ) { this . ioSocket . on ( eventName , callback ) ; } once ( eventName , callback ) { this . ioSocket . once ( eventName , callback ) ; } connect ( ) { return this . ioSocket . connect ( ) ; } disconnect ( close ? ) { return this . ioSocket . disconnect . apply ( this . ioSocket , arguments ) ; } emit ( eventName , data ? , callback ? ) { return this . ioSocket . emit . apply ( this . ioSocket , arguments ) ; } removeListener ( eventName , callback ? ) { return this . ioSocket . removeListener . apply ( this . ioSocket , arguments ) ; } removeAllListeners ( eventName ? ) { return this . ioSocket . removeAllListeners . apply ( this . ioSocket , arguments ) ; } /** create an Observable from an event */ fromEvent < T > ( eventName ) { this . subscribersCounter ++ ; return Observable . create ( ( observer ) => { this . ioSocket . on ( eventName , ( data ) => { observer . next ( data ) ; } ) ; return ( ) => { if ( this . subscribersCounter === 1 ) this . ioSocket . removeListener ( eventName ) ; } ; } ) . share ( ) ; } fromEventOnce < T > ( eventName ) { return new Promise < T > ( resolve => this . once ( eventName , resolve ) ) ; } }