blob: 1a7efa87dc564c92d85e98e09f9939df8485b11d (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
import { Injectable } from '@angular/core';
import { ConstantBackoff, Websocket, WebsocketBuilder } from 'websocket-ts';
import { API_SETTINGS } from 'src/config';
@Injectable({
providedIn: 'root'
})
export class WebSocketService {
ws?: Websocket;
private handlers: Function[] = [];
constructor() {
this.ws = new WebsocketBuilder(API_SETTINGS.apiWSUrl)
.withBackoff(new ConstantBackoff(120000))
.onOpen((i, e) => { /*console.log('WS: Connected to ' + API_SETTINGS.apiWSUrl)*/ })
.onMessage((i, e) => {
console.log('WS MESSAGE: ', e.data);
this.handlers.forEach(handler => {
handler(e.data);
})
})
.onClose((i, e) => { /*console.log('WS: Connection closed!')*/ })
.build();
}
send(msg: string) {
this.ws?.send(msg);
}
addHandler(handler: Function) {
this.handlers.push(handler);
}
removeHandler(handler: Function) {
this.handlers.splice(this.handlers.indexOf(handler), 1);
}
}
|