【问题标题】:Show data while it's being sent to the backend在发送到后端时显示数据
【发布时间】:2018-12-14 12:55:33
【问题描述】:

我正在尝试解决用户体验问题。

我正在使用 Ionic、Angular 和 Firebase 构建一个聊天应用程序。

我遇到的问题是,当用户发送消息时,该消息只有在成功发送到服务器后才会出现。

因此,这意味着如果您的连接速度较慢,则在成功发送第一条消息之前,您将无法键入下一条消息。

这是我的简化 HTML:

//For viewing messages
<div *ngFor="let message of messageFeed; let in = index">
  <div class="messageCont">
    <div class="messageBubble"
      [ngClass]="{'fromMe': message.uid == userData.uid, 'fromYou': message.uid != userData.uid}">
        {{message.text}}
      </div>
    </div>

  </div>

//For sending messages
<div>
<ion-item>
  <ion-textarea id="replyTextarea" [(ngModel)]="messageText" autocorrect="on" maxlength="450" (input)='charCount($event.target, false)' placeholder="Write something nice..."></ion-textarea>
  </ion-item>
<button type="button" id="postReplyBtn" (tap)="sendMessage()" class="glowBtn white" ion-button outline>Send</button>
</div>

这是我的 JS:

sendMessage() {
    let date = new Date().getTime();
    let messageKey = firebase.database().ref().push().key;
    let messageData = {
      text: this.msg,
      uid: this.userData.uid,
      recipient: this.recipient,
      created: date,
      messageId: messageKey,
    };
    this.database.list('threads/' + this.threadId + '/messages').set(messageKey, messageData).then(() => {
      console.log("Message Sent!")
      this.messageText = "";
      this.content.scrollToBottom(100);
      this.messageFeed.push(messageData)
    }, function(error) {
      console.log(error)
    });
  }

所以,如您所见,messageText 在消息发送成功时清除,messageFeed 在消息发送成功时获得一个新项目。

但我想要的是messageFeed 在单击“发送”后立即获得一个项目,然后在 实际 发送该项目时需要将其删除。因为在ngOnInit()我有这个代码:

getChatMsg() {
    this.getChat = this.database.database.ref('/threads/' + this.threadId + '/messages/')
      .orderByChild('created')
      .limitToLast(25);
      this.getChat.on('child_added', (snapshot) => {
this.messageFeed.push(snapshot.val());

});
}

加载最新消息。

这有意义吗?如何在messageFeed 中显示仍在发送的消息,以便用户可以在服务器接收消息时发送任意数量的消息...

【问题讨论】:

    标签: javascript angular firebase firebase-realtime-database


    【解决方案1】:

    set() 操作已经异步完成,但它的then() 回调只有在服务器确认完成后才会被调用。由于您想尽快清除输入,因此应将该代码移出 then() 回调。

    比如:

    this.database.list('threads/' + this.threadId + '/messages').set(messageKey, messageData).then(() => {
      console.log("Message committed on server")
    }, function(error) {
      console.log(error)
    });
    console.log("Message Sent!")
    this.messageText = "";
    this.content.scrollToBottom(100);
    this.messageFeed.push(messageData)
    

    【讨论】:

      【解决方案2】:

      您可以将该消息推送到 messageFeed,并利用webWorkers 来使用低或离线模式。一旦 webWorker 可以成功发送数据,然后附加一些图标(仔细检查)以指示该消息已发送。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-18
        • 1970-01-01
        • 2022-01-28
        相关资源
        最近更新 更多