I'm using ngx-socket-io on the client in my Angular app. I've followed the setup in the "How to use" section.
I'm trying to emit an event to all connected clients when one client connects using this code:
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
io.on('connect', socket => {
io.emit('foo', 'foo-event');
});
However the clients never receives this event when doing:
constructor(
private socket: Socket
) {
this.socket.fromEvent('foo')
.subscribe((e) => {
console.log(e);
});
}
However if I change the server code to:
io.on('connect', socket => {
socket.on('foo', () => {
io.emit('foo', 'foo-event');
});
});
And the client code to:
constructor(
private socket: Socket
) {
this.socket.emit('foo');
this.socket.fromEvent('foo')
.subscribe((e) => {
console.log(e);
});
}
Then it works as expected.
Why can't I just emit an event and receive it on the client without emitting an event from the client first like in the second example?
According to this answer, I think you should use
connection
event instead becauseconnect
emits just before a successful connection. Thus you can't emit new event.