首页 > 解决方案 > Ionic Firestore 聊天 - 无法不断检查更新

问题描述

目前,我是 Ionic 的新手,我正在尝试为我正在开发的应用程序实现聊天服务。我想尝试使用firestore,这就是我到目前为止所拥有的。

我已经设法从firestore读取和接收消息,但只有在我发送消息之后。

换句话说,检索消息的功能只有在我单击发送按钮后才会激活。

我想知道是否有办法让我不断检查 Firestore 的更新,以便聊天可以“实时”更新。

这是我用于接收聊天消息的代码。我已将它们放在 ionviewwilload() 中,以便在进入聊天室以及单击发送消息时接收所有消息。

retrieveCollection() : void
  {
     this._DB.getChatMessages(this._COLL,this._COLL2)
     .then((data) =>
     {
        console.log(data);
        // IF we don't have any documents then the collection doesn't exist
        // so we create it!
        if(data.length === 0)
        {
          //  this.generateCollectionAndDocument();
        }

        // Otherwise the collection does exist and we assign the returned
        // documents to the public property of locations so this can be
        // iterated through in the component template
        else
        {
           this.chats = data;
        }
     })
     .catch();
  }

然后将 getchatmessages 函数链接到我的提供程序,然后从 firestore 检索我的消息,然后将其作为承诺返回。

 getChatMessages(collectionObj: string, collectionObj2) : Promise<any>{    
    let user                : string        = firebase.auth().currentUser.uid;
    return new Promise((resolve, reject) => {


        this._DB.collection(collectionObj).doc(collectionObj2).collection("messages")
          .orderBy("sendDate", "asc")  
          .onSnapshot
          ((querySnapshot) => {
            let obj : any = [];
            querySnapshot 
            .forEach(function(doc) { 
              console.log(typeof doc);
              console.log(doc);
              obj.push({
                id : doc.id,
                message : doc.data().message,
                type : doc.data().type,
                user :doc.data().user,
                image: doc.data().image
              });
            });

            resolve(obj);
          })

        });
      }

所以我的问题是询问是否有我在文档中遗漏的特殊方法或功能,可以让我不断检查聊天应用程序中的更新。

非常感谢回复的人。

标签: firebaseionic-frameworkionic3google-cloud-firestore

解决方案


推荐阅读