I am trying to create an application using socket with Angular and node.js as backend application. In the backend I can see that connection is getting established/disconnected but not able to read events.
this is my server side node.js code:
const server = require("http").createServer();
const io = require("socket.io")(server);
io.on("connection", (client) => {
//console.log(client);
client.emit("message", "hellow world");
client.on("message", (data) => {
console.log(data);
client.emit("message", "hellow world");
});
client.on("disconnect", () => {});
});
server.listen(3000);
this is my service file added in Angular codebase:
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { io, Socket } from "socket.io-client";
@Injectable()
export class ChatService {
private socket: Socket;
constructor() {
this.socket = io("http://127.0.0.1:3000");
this.socket.on("connect", function () {
console.log("Connected!");
});
}
// EMITTER
sendMessage(msg: string) {
// this.socket.connect();
console.log(this.socket);
this.socket.emit("message", { message: msg });
}
// HANDLER
onNewMessage() {
return new Observable((observer) => {
this.socket.on("message", (msg) => {
console.log(msg);
observer.next(msg);
});
});
}
}
While logging this.socket, i can see the following object:
acks: {}
connected: false
disconnected: true
flags: {}
ids: 0
io: Manager {nsps: {…}, subs: Array(1), opts: {…}, _reconnection: true, _reconnectionAttempts: Infinity, …}
nsp: "/"
Whats wrong with my code? Thank you in advance.