I am currently developing a real-time chat application using Angular and Node.js. The backend is powered by nodejs and I am utilizing socket.io for communication.
Server Side
io.on('connection', (socket) => {
socket.on('new-message', (message) => {
io.emit(message);
});
});
Client Side
Service
private url = 'http://localhost:3000';
private socket;
constructor( private httpClient: HttpClient ) {
this.socket = io(this.url);
}
public sendMessage(message:Message){
this.socket.emit('new-message',message);
}
public getMessages = () => {
return new Observable(observer => {
this.socket.on('new-message', (message) => {
observer.next(message);
});
});
}
Component
messages:any[]=[];
constructor(private chatService:ChatService){}
ngOnInit(): void {
this.chatService.getMessages()
.subscribe((message:any)=>{
this.messages.push(message);
})
onSubmit(){
//extracting message from the input form (not relevant i think i can add it if suggested)
this.chatService.sendMessage(tosend);
}
component.html
<div *ngFor="let m of messages">
{{m.text}}
</div>
<! -- a form to send messages -->