Skip to content
Snippets Groups Projects
Select Git revision
  • dd02165083dccea40c0e34b2bd859b0d31206758
  • main default protected
  • documentation
  • admin_rights_refactor
4 results

socket.service.ts

Blame
  • Forked from an inaccessible project.
    socket.service.ts 2.27 KiB
    import { Injectable } from '@angular/core';
    import { Socket } from 'ngx-socket-io';
    import { AuthenticationService } from './authentication.service';
    import { BehaviorSubject } from 'rxjs';
    import { QuestionsService } from './questions.service';
    import { Answer, Question } from '../Types/types';
    import { HttpClient } from '@angular/common/http';
    
    const ROUTE = "http://0.0.0.0:30992/API/v1"
    
    @Injectable({
      providedIn: 'root'
    })
    export class SocketService {
    
      private _playerNumber = new BehaviorSubject<number>(0);
      private _gameStart = new BehaviorSubject<boolean>(false);
      private _currentQuestion = new BehaviorSubject<string>("");
      private _currentAnswers = new BehaviorSubject<Answer[]>([]);
    
      constructor(
        private socket: Socket
      ) {
        this.socket.ioSocket.io.opts.query = { Authorization: localStorage.getItem("token")};
        this.recievePlayerNumber();
        this.recieveGameStatus();
        this.recieveQuestion();
      }
    
      get playerNumber() {
        return this._playerNumber.asObservable();
      }
    
      get gameStart() {
        return this._gameStart.asObservable();
      }
    
      get questionID() {
        return this._currentQuestion.asObservable();
      }
    
      get answers() {
        return this._currentAnswers.asObservable();
      }
    
      refreshSocketToken(): void {
        this.socket.ioSocket.io.opts.query = { Authorization: localStorage.getItem("token")};
      }
    
      joinRoom(): void {
        this.refreshSocketToken();
        this.socket.emit("Join Room");
      }
    
      leaveRoom(): void {
        this.refreshSocketToken();
        this.socket.emit("Leave Room");
      }
    
      recieveGameStatus() {
        this.socket.on("Game Start", ()=> {
          this._gameStart.next(true);
        })
      }
    
      recievePlayerNumber(): void {
        this.socket.on("Players Waiting", number => {
          this._playerNumber.next(number);
          console.log(this.playerNumber);
        })
      }
    
      recieveQuestion(): void {
        this.socket.on("Question", question => {
          
          this._currentQuestion.next(question);
        })
    
        this.socket.on("Answers", answers => {
          this._currentAnswers.next(answers);
        })
      }
    
      disconnectSocket() {
        this.socket.disconnect();
      }
    
      sendMessage(text: string): void {
        this.refreshSocketToken();
        this.socket.emit(text);
      }
    
      sendAnswer(answer: Answer): void {
        this.refreshSocketToken();
        this.socket.emit("Answer", answer);
      }
    
    }