0

I am building an app with ngx socket io which connects properly and works fine. This app is securized and it connects to an URL including the username. As the URL is different for each user I have defined a custom socket with my config:

import { Injectable } from "@angular/core";
import { Socket } from "ngx-socket-io";
import { environment } from "src/environments/environment";
import { AuthService } from "./auth.service";

@Injectable({
  providedIn: 'root'
})
  export class CustomSocket extends Socket {

    socketStatus : boolean = false;

    constructor(private authServ: AuthService) {

      super({
        url: environment.wsUrl + authServ.getUsuarioAutenticado() ?? "",

        options: { transports: ['polling']
        }
      })
     }

  }

This custom socket is called from the websocket service and works as a normal socket:

import { Injectable } from '@angular/core';
import { CustomSocket } from './customSocket';

@Injectable({
  providedIn: 'root'
})
export class WebsocketService {

  socketStatus : boolean = false;

  constructor(private socket: CustomSocket) {
    this.checkStatus()

   }


  checkStatus() {

    this.socket.on('connect', () => {
      console.log('Conectado al servidor');
      this.socketStatus = true;
    });

    this.socket.on('disconnect', () => {
      console.log('Desconectado del servidor');
      this.socketStatus = false;
    });
  }

  emitir( evento: string, payload?: any, callback?: Function ) {

    console.log('Emitiendo', evento);
    // emit('EVENTO', payload, callback?)
    this.socket.emit( evento, payload, callback );

  }

  listen( evento: string ) {
    return this.socket.fromEvent( evento );
  }

  disconnect () {
    this.socket.disconnect()
  }

  connect () {
    this.socket.connect()
  }
}

And I print in a list all the elements I get from the socket in real time.

The problem comes when I log out as if I log in a different user without reloading the page, It gets connected to the URL of the previous user, as the CustomSocket service has already been triggered and will not trigger again. I want to kill that instance of the service when logged out or something equivalent.

I know that if I would use the custom socket in a component instead of another Injectable, I could just remove the provideIn: 'root', and add as a provider in the component, but I believe this can not be done in another injectable.

Any help is welcome, thank you.

Videgain
  • 155
  • 3
  • 15

0 Answers0