import { Injectable } from '@angular/core' ; import * as Rx from 'rxjs' ; @ Injectable ( { providedIn : 'root' , } ) export class WebsocketService { private subject : Rx . Subject < MessageEvent > ; public connect ( url ) { if ( ! this . subject ) { this . subject = this . create ( url ) ; } return this . subject ; } private create ( url ) { const ws = new WebSocket ( url ) ; ws . onerror = ( event ) => { console . log ( 'WebSocket Connection Failed with message' , event . type ) ; return false ; } ; const observable = Rx . Observable . create ( ( obs ) => { ws . onmessage = obs . next . bind ( obs ) ; ws . onerror = obs . error . bind ( obs ) ; ws . onclose = obs . complete . bind ( obs ) ; return ws . close . bind ( ws ) ; } ) ; const observer = { next : ( data ) => { if ( ws . readyState === WebSocket . OPEN ) { ws . send ( JSON . stringify ( data ) ) ; } else { console . log ( 'not ready yet' ) ; setTimeout ( ( ) => { this . subject . next ( data ) ; } , 500 ) ; } } } ; return Rx . Subject . create ( observer , observable ) ; } }