Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable } from '@angular/core';
- import { Subscription, BehaviorSubject } from 'rxjs';
- import { WebSocketSubject } from 'rxjs/observable/dom/WebSocketSubject';
- import { AuthService } from './auth.service';
- @Injectable({
- providedIn: 'root'
- })
- export class SocketService {
- private socketSubject$: WebSocketSubject<any>;
- private subscription: Subscription;
- private readonly testSubject$ = new BehaviorSubject<any[]>([]);
- constructor(
- private readonly authService: AuthService,
- ) {
- this.authService.loggedUser$.subscribe(
- (user) => {
- !!user ? this.start() : this.stop();
- }
- );
- }
- get test$() {
- return this.testSubject$.asObservable();
- }
- private start() {
- this.socketSubject$ = new WebSocketSubject(`ws://localhost:8081/`);
- this.subscription = this.socketSubject$.
- subscribe(
- (data) => {
- console.log(data);
- this.testSubject$.next(data);
- }
- );
- // authenticate
- this.socketSubject$.next({ token: localStorage.getItem('token') || '' });
- }
- private stop() {
- if (this.subscription) {
- this.subscription.unsubscribe();
- }
- this.socketSubject$.complete();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement