import { Injectable } from '@angular/core'; import * as io from 'socket.io-client'; @Injectable() export class CfSocketService { static socket; static endpoint; static configured = false; static configure(config: any) { let { endpoint } = config; this.endpoint = endpoint; this.socket = io.connect(endpoint); this.configured = true; } subscribe(type, callback) { if (CfSocketService.configured) { CfSocketService.socket.on(type, data => { callback(data); }); } else { console.error('You must configure CfSocketService prior to using it.'); } } unsubscribe(type) { if (CfSocketService.configured) { CfSocketService.socket.unsubscribe(type); } else { console.error('You must configure CfSocketService prior to using it.'); } } subscribeToRoom(roomName, type, callback) { const roomConnection = io.connect(CfSocketService.endpoint + '/' + roomName); if (CfSocketService.configured) { roomConnection.on(type, data => { callback(data); }); } else { console.error('You must configure CfSocketService prior to using it.'); } } constructor() { } }