import { Injectable } from '@angular/core'; import { v4 as uuidv4 } from 'uuid'; @Injectable({ providedIn: 'root' }) export class SocketInterfaceService { private socket!: WebSocket; private url = '' private connected = false private callBacks: { type: 'Offline' | 'Online' | 'Open' , object?: string funx: Function }[] = [] private msgQueue : { message: object, requestId: string }[] = [] private msgQueueIds = [] private disconnect: Function constructor() { } registerCallback(type: 'Offline' | 'Online' | 'Open', funx: Function, object = '') { this.callBacks.push({ type, funx, object }) } connect(url) { this.url = url this.socket = new WebSocket(this.url); // bind function this.socket.onopen = this.onopen; this.socket.onmessage = this.onmessage; this.socket.onclose = this.onclose; this.socket.onerror = this.onerror; } onopen() { this.connected = true // send all saved data due to internet connection this.msgQueue.forEach((item, index, object) => { this.send(item.message, item.requestId); object.splice(index, 1); this.msgQueueIds.slice(index, 1) }) } send(message: object, requestId = uuidv4()) { if (this.connected === false) { // save data to send when back online this.msgQueue.push({message, requestId}) this.msgQueueIds.push(requestId) } else { let messageStr = JSON.stringify(message) this.socket.send(messageStr) } return requestId } onmessage(event: any) { console.log('event.data', JSON.parse(event.data)) } onclose(event: any) { this.connected = false console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`); setTimeout(()=>{ this.connect(this.url) }, 500) } onerror = (event: any) => { console.log(`[error] ${event.message}`); } }