mirror of
https://code.equilibrium.co.ao/ITO/doneit-web.git
synced 2026-04-18 20:47:54 +00:00
50 lines
1.0 KiB
TypeScript
50 lines
1.0 KiB
TypeScript
import { Injectable } from '@angular/core';
|
|
import * as Rx from "rxjs/Rx";
|
|
import { Observable, Subject } from "rxjs/Rx";
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class WebsocketService {
|
|
|
|
message = '';
|
|
public messages: Subject<any>;
|
|
currentUser = '';
|
|
private subject: Rx.Subject<MessageEvent>;
|
|
|
|
constructor() {
|
|
|
|
}
|
|
|
|
public connect(url): Rx.Subject<MessageEvent> {
|
|
if (!this.subject) {
|
|
this.subject = this.create(url);
|
|
|
|
}
|
|
return this.subject;
|
|
}
|
|
|
|
private create(url): Rx.Subject<MessageEvent> {
|
|
let ws = new WebSocket(url);
|
|
|
|
|
|
|
|
|
|
let observable = Rx.Observable.create((obs: Rx.Observer<MessageEvent>) => {
|
|
ws.onmessage = obs.next.bind(obs);
|
|
ws.onerror = obs.error.bind(obs);
|
|
ws.onclose = obs.complete.bind(obs);
|
|
return ws.close.bind(ws);
|
|
});
|
|
let observer = {
|
|
next: (data: Object) => {
|
|
if (ws.readyState === WebSocket.OPEN) {
|
|
ws.send(JSON.stringify(data));
|
|
}
|
|
}
|
|
};
|
|
return Rx.Subject.create(observer, observable);
|
|
}
|
|
|
|
}
|