我是 typescript 的新手,我在一个 angular 2 元素中工作,我正在尝试做一个聊天框,新消息应该在底部,旧消息应该排成一行,而不是这样:
此外,我希望他们不要离开 div,当它已满时,我只想使用滚动条来查看旧消息...
这是我的:
聊天室组件.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>
聊天室.component.css:
.chatbox{
width: 100%;
height: 500px;
}
.chatbox p{
text-align: bottom;
}
聊天室组件.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();
});
}
}
服务器.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);
};
};
最佳答案
您可以通过简单地使用添加日期、数组索引等对数组进行排序或将 push 替换为 unshift 以将新消息添加到数组的开头来反转消息的顺序。
有关简单的订单管道,请参见:angular 2 sort and filter
将消息本身对齐到屏幕或容器的底部(使用 css)
.chatbox{
display:table;
}
.chatbox p{
display:table-cell;
vertical-align:bottom;
}
关于html - Angular 2聊天框消息从下到上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41468324/