Currently, I am in the process of learning how to integrate live chat into an Angular project using Socket.IO. Following a tutorial that I stumbled upon, which can be found here.
Incorporating an input box within my component has allowed me to successfully send messages from the component to the server.
https://i.sstatic.net/p50Wn.png
The obstacle I'm facing now is figuring out how to use 'emit' to send the message back to the user and update the DOM accordingly.
Let me walk you through my code. Although the chat box does not currently have its own component, it will eventually. Below is the TypeScript code for where the chat box resides. Keep in mind this is part of creating a card game so you may come across references to decks and dealers.
import { Component, OnInit, OnDestroy } from '@angular/core';
import { DealerService } from '../services/dealer.service';
import { ChatService } from '../services/chat.service';
@Component({
selector: 'app-blackjackgame',
templateUrl: './blackjackgame.component.html',
styleUrls: ['./blackjackgame.component.css']
})
export class BlackjackgameComponent implements OnInit, OnDestroy {
constructor(private dealer: DealerService, private chat: ChatService) { }
ngOnInit() {
this.dealer.generateDeck();
this.dealer.shuffle(5);
this.chat.messages.subscribe(msg => {
console.log(msg);
});
}
// Sending a message
sendMessage(message: string) {
this.chat.sendMsg(message);
}
// Unsure if this is the correct approach
updateMessages(message: string) {
console.log('message was emitted: ' + message);
}
ngOnDestroy() {
}
}
I utilize two main services, namely the chat service and WebSocket service.
The chat service is structured as follows:
import { Injectable } from '@angular/core';
import { WebsocketService } from './websocket.service';
import { Observable, Subject } from 'rxjs/Rx';
@Injectable()
export class ChatService {
messages: Subject<any>;
constructor(private wsService: WebsocketService) {
this.messages = <Subject<any>>wsService
.connect()
.map((response: any): any => {
return response;
});
}
sendMsg(msg){
this.messages.next(msg);
}
}
As for the WebSocket service:
import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs/Observable';
import * as Rx from 'rxjs/Rx';
import { environment } from '../../environments/environment';
@Injectable()
export class WebsocketService {
private socket;
constructor() { }
connect(): Rx.Subject<MessageEvent> {
this.socket = io(environment.ws_url);
const observable = new Observable(observer => {
this.socket.on('message', (data) => {
console.log('Received a message from websocket service');
observer.next(data);
});
return () => {
this.socket.disconnect();
};
});
const observer = {
next: (data: Object) => {
this.socket.emit('message', JSON.stringify(data));
}
};
return Rx.Subject.create(observer, observable);
}
}
Lastly, there's a WebSocket server written in plain JavaScript. The snippet above provides an overview, but here is the complete code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('Connection made');
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(5000, function(){
console.log('listening on *:5000');
});
Essentially, my WebSocket server logs when receiving a message. My query pertains to sending information back in response and updating the DOM within the component based on the WebSocket-emitted messages. Any guidance would be immensely appreciated since I am relatively inexperienced with this technology.