【问题标题】:Angular 2 chatbox message from bottom to top从下到上的Angular 2聊天框消息
【发布时间】:2017-05-19 00:14:20
【问题描述】:

我是使用打字稿的新手,我正在从事一个 Angular 2 项目,我正在尝试做一个聊天框,其中新消息应该在底部,旧消息排成一行而不是这样:

另外,我希望他们不要离开 div,当它已满时,我只想使用滚动查看旧消息...

这就是我所拥有的:

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);
    };


};

【问题讨论】:

  • 服务如何返回数据getChatMessages
  • 使用 getChatMessages 添加了 websocket 服务
  • 文本对齐:底部不可用尝试垂直对齐,检查此w3schools.com/cssref/pr_pos_vertical-align.asp
  • @enucar 尝试了垂直对齐:text-bottom 和 bottom 并且没有工作
  • 谢谢您...还有任何将它们固定在底部的想法吗?

标签: html css node.js angular typescript


【解决方案1】:

您可以通过简单地使用添加日期、数组索引等对数组进行排序或将 push 替换为 unshift 以将新消息添加到数组的开头来反转消息的顺序。

查看这个简单的订单管道:angular 2 sort and filter

将消息本身与屏幕或容器的底部对齐(使用 css)

.chatbox{
  display:table;
}
.chatbox p{
  display:table-cell;
  vertical-align:bottom;
}

【讨论】:

  • 谢谢您...还有任何将它们固定在底部的想法吗?
  • 可以在 css 中使用显示表格和垂直对齐底部来完成。
    这里的内容
    #parent {display: table} #child { display: table-cell;垂直对齐:底部; }
  • M,我试过了,但是单元格都在同一行中...我设法使它们每行一个,但也有一个问题...表格自动调整大小,所以第一个消息之间有很大的空间,直到有足够的消息使它看起来像一个体面的

  • 这一切都可以用纯 css 修复。有关示例,请参见此 JSFiddle。还要避免使用 p 标签来显示项目列表。 jsfiddle.net/4o07aqj3/5
  • 我刚刚注意到这个解决方案有一个问题......它工作但溢出变得混乱......如果有很多消息而不是滚动它只会让聊天变得更大
【解决方案2】:

这应该是一个普通的 CSS 解决方案。将固定高度设置为div.chatbox 并添加overflow-y: auto。至于留在底部的消息,您可以添加position: relativediv.chatboxposition: absolute; bottom: 0div.chatbox &gt; p

像这样:

.chatbox {
    height: 400px; /* reasonable estimate */
    overflow-y: auto; /* show scrollbar only when text overflows vertically */
    position: relative;
}

.chatbox > p {
    position: absolute;
    bottom: 0;
}

编辑:要颠倒顺序,您可以创建自定义管道或使用 ng-pipes 模块 (Angular 2 ngFor - reverse order of output using the index) 中的预构建管道

自定义(http://www.devsplanet.com/question/35703258 提供):

@Pipe({
  name: 'reverse'
})
export class ReversePipe {
  transform(value) {
    return value.slice().reverse();
  }
}

干杯!

【讨论】:

  • 成功了,谢谢 :) 你知道我怎样才能颠倒消息的顺序吗?
  • 谢谢您...还有任何将它们固定在底部的想法吗?
  • @JoãoSilva pin 用什么方式?
  • 消息不是从上到下显示,而是从下到上显示...这就是我的意思是颠倒顺序...
猜你喜欢
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-09
  • 2019-04-09
  • 1970-01-01
  • 1970-01-01
  • 2013-08-28
相关资源
最近更新 更多