Guest User

Untitled

a guest
May 21st, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. import { Injectable } from '@angular/core';
  2. import { BehaviorSubject, Observable, Subject } from 'rxjs/Rx';
  3. import * as Stomp from '@stomp/stompjs';
  4. import * as SockJS from 'sockjs-client';
  5. import { ApiWorkerService } from '../api/api-worker.service';
  6. import { filter, map } from 'rxjs/operators';
  7.  
  8. @Injectable({
  9. providedIn: 'root'
  10. })
  11. export class WebSocketService {
  12. private messageSubject: Subject<{ code: string, body: any }> = new Subject<{ code: string, body: any }>();
  13. private state: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
  14. private readonly ws: WebSocket;
  15. private readonly client: Stomp.Client;
  16.  
  17. constructor(private api: ApiWorkerService) {
  18. this.ws = new SockJS(this.api.prepareUrl('ws'));
  19. this.client = Stomp.over(this.ws);
  20. this.client.connect({}, () => {
  21. this.state.next(true);
  22. this.client.subscribe('/subscribe', message => {
  23. this.messageSubject.next({
  24. code: message.headers['code'],
  25. body: message.body
  26. });
  27. });
  28. }, () => {
  29. console.error('WebSocket connection error');
  30. this.state.next(false);
  31. });
  32. }
  33.  
  34. public getObservable<T>(code: string): Observable<T> {
  35. return this.messageSubject.asObservable().pipe(
  36. filter(data => {
  37. return data.code === code;
  38. }),
  39. map(data => {
  40. return data.body as T;
  41. })
  42. );
  43. }
  44. }
Add Comment
Please, Sign In to add comment