import { Injectable } from '@angular/core' ; import { Subscriber } from 'rxjs/Subscriber' ; import { Observable } from 'rxjs/Observable' ; @ Injectable ( ) export class WebsocketService { private ws : WebSocket ; createObservableSocket ( url , openSubscriber ) { this . ws = new WebSocket ( url ) ; return new Observable ( observer => { this . ws . onmessage = event => observer . next ( event . data ) ; this . ws . onerror = event => observer . error ( event ) ; this . ws . onclose = event => observer . complete ( ) ; this . ws . onopen = event => { openSubscriber . next ( ) ; openSubscriber . complete ( ) ; } ; return ( ) => this . ws . close ( ) ; } ) ; } send ( message ) { this . ws . send ( JSON . stringify ( message ) ) ; } }