Clientside I used Angular 6 and Serverside i used node.js.
Here in angular 6 console it print message and
socket.io id({message: "Hello World", id: "6An-ctwlwbZZWrfMAAAB"})
after using below code.
this code is right or any change in this code bcoz I am not sure about this code kindly help to make correct this.
and another query is I have more than 15 components in my project so how to make common use this socket.io
for all components or I have to import this app.component.ts
code in all another component.
app.js(serverside)
after installing (npm i socket.io)
const express = require('express');
var app = express();
const http = require('http');
const socketIo = require('socket.io');
const server = http.Server(app);
const io = socketIo(server);
server.listen(3000,function(req,res){
console.log("listen at 3000!");
});
io.on('connection',(socket) => {
socket.emit('hello',{
message : 'Hello World',id: socket.id
})
});
app.component.ts(clientside)
after installing (npm i socket.io)
import * as socketIo from 'socket.io-client';
export class AppComponent implements OnInit {
ngOnInit(){
const socket = socketIo('http://localhost:3000/');
socket.on('hello',(data) => console.log(data));
}
}
}
Create Service and turn your socket data into Observable stream
Then Call from component
App.component.ts
You can create a service for working with a socket. E.g (of course this is a very simple example):
And use it in any components:
The one way to achieve this mechanism is using
ngx-socket-io
, connect your node server at the module level or root level i have implemented like belowapp.module.ts code
create one service which handles your incoming and outgoing traffic.
Update your code in your component file