As a newcomer to using typescript, I am currently working on an angular 2 project and facing some challenges with creating a chatbox. My goal is to have new messages displayed at the bottom while pushing the old ones up one line at a time, as shown in this example:
I also want to ensure that the messages stay within the div container and when it reaches full capacity, I would like a scroll feature to view older messages.
This is the current setup I have:
chatroom.component.html:
<h2>Player Notifications</h2>
<p *ngFor="let m of playersChannel">{{m}}</p>
<h2>Chat history</h2>
<div class='chatbox'>
<p *ngFor="let m of chatChannel">{{m}}</p>
</div>
chatroom.component.css:
.chatbox{
width: 100%;
height: 500px;
}
.chatbox p{
text-align: bottom;
}
chatroom.component.ts:
import { Component, OnInit } from '@angular/core';
import {WebSocketService } from './websocket.service';
@Component({
moduleId: module.id,
selector: 'chat',
styleUrls: [ 'chatroom.component.css' ],
templateUrl: 'chatroom.component.html'
})
export class ChatroomComponent implements OnInit {
playersChannel: string[] = [];
chatChannel: string[] = [];
constructor(private websocketService: WebSocketService){
}
ngOnInit() {
this.websocketService
.getChatMessages()
.subscribe((m:any) => this.chatChannel.push(<string>m));
this.websocketService
.getPlayersMessages()
.subscribe((m:any) => this.playersChannel.push(<string>m));
}
}
websocket.service.ts:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {Observable} from 'rxjs/Observable';
import * as io from 'socket.io-client';
@Injectable()
export class WebSocketService {
private socket: SocketIOClient.Socket;
constructor() {
if (!this.socket) {
this.socket = io(`http://${window.location.hostname}:${window.location.port}`);
}
}
sendChatMessage(message: any) {
this.socket.emit('chat', this.getUserTime() + message);
}
getPlayersMessages(): Observable<any> {
return this.createObservable('players');
}
getChatMessages(): Observable<any> {
return this.createObservable('chat');
}
getUserTime(){
let now = Date.now();
let date = new Date(now);
let hours = date.getHours();
let mins = date.getMinutes();
let secs = date.getSeconds();
return hours + ":" + mins + ":" + secs + ": ";
}
private createObservable(channel: string): Observable<any> {
return new Observable((observer:any) => {
this.socket.on(channel, (data:any) => {
observer.next(data);
});
return () => this.socket.disconnect();
});
}
}
server.websocket.ts:
const io = require('socket.io');
export class WebSocketServer {
public io: any;
public init = (server: any) => {
this.io = io.listen(server);
this.io.sockets.on('connection', (client: any) => {
client.emit('players', Date.now() + ': Welcome to battleship');
client.broadcast.emit('players', Date.now() + ': A new player has arrived');
client.on('chat', (data) => this.io.emit('chat', data));
});
};
public notifyAll = (channel: string, message: any) => {
this.io.sockets.emit(channel, message);
};
};