Files
doneit-web/src/app/services/socket/interface/socket-interface.service.ts
T

76 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-01-07 09:03:15 +01:00
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SocketInterfaceService {
private socket!: WebSocket;
private url = ''
private connected = false
private callBacks: {
2022-01-07 11:21:14 +01:00
type: 'Offline' | 'Online' | 'Open' ,
2022-01-07 09:03:15 +01:00
object?: string
funx: Function
}[] = []
private msgQueue = []
constructor() { }
2022-01-07 11:21:14 +01:00
registerCallback(type: 'Offline' | 'Online' | 'Open', funx: Function, object = '') {
this.callBacks.push({
type,
funx,
object
})
}
2022-01-07 09:03:15 +01:00
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;
}
2022-01-07 11:21:14 +01:00
onopen() {
this.connected = true
// send all saved data due to internet connection
this.msgQueue.forEach((item, index, object) => {
this.send(item);
object.splice(index, 1);
})
}
2022-01-07 09:03:15 +01:00
send(message: object) {
2022-01-07 11:21:14 +01:00
console.log(this.connected, message)
if (this.connected === false) { // save data to send when back online
2022-01-07 09:03:15 +01:00
this.msgQueue.push(message)
} else {
let messageStr = JSON.stringify(message)
this.socket.send(messageStr)
}
}
2022-01-07 11:21:14 +01:00
onmessage(event: any) {
console.log('event.data', JSON.parse(event.data))
2022-01-07 09:03:15 +01:00
}
onclose(event: any) {
2022-01-07 11:21:14 +01:00
this.connected = false
2022-01-07 09:03:15 +01:00
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}`);
}
}