【发布时间】:2021-07-04 15:26:16
【问题描述】:
我正在使用 Ionic Angular Firebase 构建一个聊天应用程序,当我发送一条新消息时,我调用了 scrollToBottom() 函数。问题是聊天窗口在到达底部之前会先到顶部(非常快,不到 1 秒)。 所以感觉就像应用程序被窃听了,因为当我发送消息时,它很快就直接进入顶部,然后又进入底部。
这是我的代码:
tchat.service.ts:
getChatMessages() {
return this.afs
.collection("messages", (ref) => ref.orderBy("createdAt", "asc"))
.valueChanges({ idField: "id" }) as Observable<Message[]>;}
tchat.ts:
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title>Tchat</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item *ngFor="let message of messages | async">
<ion-avatar slot="start">
<img src="{{message.img_url}}">
</ion-avatar>
<ion-label>
<h2>{{ message.from_name }} {{ message.createdAt?.toMillis() | date:'short' }}</h2>
<p>{{ message.msg }}</p>
</ion-label>
</ion-item>
</ion-list>
</ion-content>
<ion-toolbar color="light">
<ion-row class="ion-align-items-center">
<ion-col size="10">
<ion-textarea autoGrow="true" class="message-input" rows="1" maxLength="500" [(ngModel)]="newMsg"
(keydown)="handleSubmit($event)">
</ion-textarea>
</ion-col>
<ion-col size="2">
<ion-button expand="block" fill="clear" color="primary" [disabled]="newMsg === ''" class="msg-btn"
(click)="sendMessage()">
<ion-icon name="send" slot="icon-only"></ion-icon>
</ion-button>
</ion-col>
</ion-row>
</ion-toolbar>
tchat.ts:
export class TchatPage implements OnInit, AfterViewChecked {
@ViewChild(IonContent) content: IonContent;
messages: Observable<any[]>;
newMsg = "";
constructor(private tchatService: TchatService) {}
ngOnInit() {
this.messages = this.tchatService.getChatMessages();
}
ngAfterViewChecked() {
this.content.scrollToBottom(200);
}
sendMessage() {
this.tchatService.addChatMessage(this.newMsg).then(() => {
this.newMsg = "";
this.content.scrollToBottom(200);
});
}
handleSubmit(event) {
if (event.keyCode === 13) {
this.sendMessage();
}
}
}
【问题讨论】: