Advertisement
Guest User

Untitled

a guest
Dec 10th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. import { Injectable } from '@angular/core';
  2. import { Subscription, BehaviorSubject } from 'rxjs';
  3. import { WebSocketSubject } from 'rxjs/observable/dom/WebSocketSubject';
  4. import { AuthService } from './auth.service';
  5.  
  6. @Injectable({
  7. providedIn: 'root'
  8. })
  9. export class SocketService {
  10. private socketSubject$: WebSocketSubject<any>;
  11. private subscription: Subscription;
  12.  
  13. private readonly testSubject$ = new BehaviorSubject<any[]>([]);
  14.  
  15. constructor(
  16. private readonly authService: AuthService,
  17. ) {
  18. this.authService.loggedUser$.subscribe(
  19. (user) => {
  20. !!user ? this.start() : this.stop();
  21. }
  22. );
  23. }
  24.  
  25. get test$() {
  26. return this.testSubject$.asObservable();
  27. }
  28.  
  29. private start() {
  30. this.socketSubject$ = new WebSocketSubject(`ws://localhost:8081/`);
  31.  
  32. this.subscription = this.socketSubject$.
  33. subscribe(
  34. (data) => {
  35. console.log(data);
  36. this.testSubject$.next(data);
  37. }
  38. );
  39.  
  40. // authenticate
  41. this.socketSubject$.next({ token: localStorage.getItem('token') || '' });
  42. }
  43.  
  44. private stop() {
  45. if (this.subscription) {
  46. this.subscription.unsubscribe();
  47. }
  48.  
  49. this.socketSubject$.complete();
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement