【问题标题】:Chat in Ionic with Cloud Firestore使用 Cloud Firestore 在 Ionic 中聊天
【发布时间】:2019-02-07 12:46:51
【问题描述】:

我正在尝试在我的应用中实现聊天页面。

在构造函数中,我询问数据库中的所有消息:

this._DB
        .getDocument("chats", this.favour.chatId)
        .then(documentSnapshot => {
          var chat = documentSnapshot.data();
          for (var key in chat) {
            chat.key = chat[key];
          }
          delete chat.key;
          this.chat = chat;
        })
        .catch(error => {
          console.log(error);
        });

并且应用程序可以使用此 html 加载消息:

<ion-item *ngFor="let messages of chat?.messages" class="chat" text-wrap [ngClass]="{'chat-partner' : messages?.askedName == localStorage?.name}">
            {{messages.message}}
        </ion-item>

要实现我在文档中看到的实时聊天,我必须使用 onSnapshot 方法:

https://firebase.google.com/docs/firestore/query-data/listen

那我用这个函数:

ionViewDidEnter() {
this._DB._DB
  .collection("chats")
  .doc(this.favour.chatId)
  .onSnapshot(function(doc) {
    this.chat = doc.data();
    console.log(this.chat);
  });
this.content.scrollToBottom();

}

但问题是console.log在控制台中显示this.chat正常,但html不刷新它:-(

我做错了什么?

提前致谢

PS:我看到可能在我使用 this._DB._DB 的 onSnapshot 函数中感到困惑,这是因为在提供程序(_DB)中我没有该功能,我将其公开以便可以在其他地方使用并且可以做测试。

【问题讨论】:

    标签: firebase ionic-framework google-cloud-firestore


    【解决方案1】:

    终于找到了解决办法。

    看起来问题是对象 this... 在组件中不同,就像在 onSnapshot 调用的函数中一样。

    我解决了创建不同的功能:

      observingChat(objectThis){
        if(objectThis.favour.chatId){
        this._DB._DB
          .collection("chats")
          .doc(objectThis.favour.chatId)
          .onSnapshot(function(doc) {
            objectThis.chat = doc.data();
            objectThis.content.scrollToBottom();
          });    
        } 
      }
    

    recibe 对象 this,并从 ionViewDidEnter() 调用它

    ionViewDidEnter() {
        this.content.scrollToBottom();
        this.observingChat(this);
      }
    

    我不知道这个对象为什么或在哪里改变......如果有人能澄清并告诉我解决方案是否正确,我将非常感激:-)

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 2020-04-17
      • 2019-11-11
      • 2019-09-10
      • 1970-01-01
      • 2018-10-06
      • 2018-12-09
      • 2020-03-27
      • 2019-04-29
      相关资源
      最近更新 更多