import { Injectable } from '@angular/core' ; import { Observable } from 'rxjs/Observable' ; import { Subject } from 'rxjs/Subject' ; import { Observer } from "rxjs/Observer" ; @ Injectable ( ) export class WebSocketService { private subject : Subject < MessageEvent > ; public connect ( url ) { if ( ! this . subject ) { this . subject = this . create ( url ) ; } return this . subject ; } private create ( url ) { let ws = new WebSocket ( url ) ; let observable = 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 ) ; } ) ; let observer = { next : ( data ) => { if ( ws . readyState === WebSocket . OPEN ) { ws . send ( JSON . stringify ( data ) ) ; } } } ; return Subject . create ( observer , observable ) ; } }