You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.7KB

  1. import { Injectable } from '@angular/core';
  2. import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
  3. import { BehaviorSubject,Subject } from "rxjs";
  4. import { config } from "../../../assets/config/config";
  5. @Injectable({
  6. providedIn: 'root'
  7. })
  8. export class SocketService {
  9. gateway = config.gateway;
  10. websocket$: WebSocketSubject<any> | undefined ;
  11. private isConnected: boolean = false;
  12. private messagesSubject$ = new Subject();
  13. public messages$ = this.messagesSubject$.asObservable();
  14. private statusSubject = new BehaviorSubject<boolean>(this.isConnected);
  15. public status$ = this.statusSubject.asObservable();
  16. constructor() {
  17. }
  18. public connect(cfg: { reconnect: boolean } = { reconnect: false }): void {
  19. if (cfg.reconnect || !this.websocket$ || this.websocket$.closed) {
  20. console.log(cfg.reconnect ? 'Reconnecting WebSocket…' : 'Trying to open a WebSocket connection…');
  21. this.websocket$ = this.getNewWebSocket();
  22. this.websocket$.subscribe((messages) => {
  23. this.messagesSubject$.next(messages);
  24. });
  25. }
  26. }
  27. close() {
  28. this.websocket$?.complete();
  29. this.websocket$ = undefined;
  30. }
  31. sendMessage(msg: any) {
  32. this.websocket$?.next(msg);
  33. }
  34. private getNewWebSocket() {
  35. return webSocket({
  36. url: this.gateway,
  37. openObserver: {
  38. next: () => {
  39. console.log('Connection ok');
  40. this.isConnected = true;
  41. this.statusSubject.next(this.isConnected);
  42. }
  43. },
  44. closeObserver: {
  45. next: () => {
  46. console.log('Connection closed');
  47. this.websocket$ = undefined;
  48. this.isConnected = false;
  49. this.connect({reconnect: true});
  50. this.statusSubject.next(this.isConnected);
  51. }
  52. },
  53. });
  54. }
  55. }