Retreive socket id from ngx-socket-io

750 views Asked by At

I've recently started using ngx-socket-io, and i've run into some difficultys as i wanted to retreive the socket id. Does anyone know how this can be done ? (I'm using the service intialization not the one in the app Module) Thank you in advance.

2

There are 2 answers

0
FBaez51 On BEST ANSWER
import { Socket } from 'ngx-socket-io';
    
constructor(private socket: Socket) {}
    
ngOnInit() {
    this.socket.on('connect', () => console.log(this.socket.ioSocket.id));
}
0
zos1000 On

You can find it in the socket instance: socket.ioSocket.id.
However you will have to wait for the socket to initialize before using it.

@Injectable({ providedIn: 'root' })
export class SocketService {
  socketId;

  constructor(private socket: Socket) {
    socket.on('connect', () => this.socketId = this.socket.ioSocket.id);
  }
}