angular - 如何在返回 onSnapshot 结果的服务中创建一个方法,然后在我的组件或 Ionic 页面中使用它?

标签 angular typescript firebase ionic3 google-cloud-firestore

我正在使用 "ionic-angular": "3.7.1"和 Firebase Cloud Firestore。每次更新、删除或添加时,我都想将所有文档都放入 Post 集合中。我知道调用 onSnapshot 方法可以获得它,所以我在服务中定义了这个方法。

getPosts(token: string){
  const userId = this.authService.getActiveUser().uid;
  let posts = [];
  return firebase.firestore().collection("Post").onSnapshot(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
          posts.push(doc.data());
        });
        console.log("Posts: ", posts.join(", "));
        return posts;
      });
}

所以在控制台中,我可以在数组 Posts 中看到我的所有帖子,但是如果在我的组件中使用 this.post.getPosts(token) 调用此方法,我会在控制台中获得此输出:

ƒ () {
  asyncObserver.mute();
  firestoreClient.unlisten(internalListener);
}

那么,我如何在服务中创建一个返回 onSnapshot 结果的方法,然后在我的组件或 Ionic 页面中使用它?

文档

https://firebase.google.com/docs/reference/js/firebase.firestore.Query?hl=es-419

https://firebase.google.com/docs/firestore/query-data/listen?hl=es-419

最佳答案

更新:

如果您需要了解如何使用 Firestore 实现通用 service/provider,请参阅 this artcile .

旧反馈:

你需要在这里使用fat arrow函数,你在这里犯了很多错误。您可以尝试下面的代码

  getPosts(token: string){
    const userId = this.authService.getActiveUser().uid;
    let posts = [];

     retrun firebase.firestore().collection("Post").get().then((querySnapshot)=> 
     {
       querySnapshot.forEach((doc)=> {
           posts.push(doc.data());
      });
        return posts;
     });
 }

Doc

关于angular - 如何在返回 onSnapshot 结果的服务中创建一个方法,然后在我的组件或 Ionic 页面中使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47046493/

相关文章:

angular - 如何在 Angular 10 中急切加载 ionic 模态

java - 如何在 Tomcat 服务器中部署 Angular 8 应用程序?

typescript - 如何为 vscode 启用严格的空检查

typescript - 确保 TypeScript 联合在整个代码中保持狭窄

ios - 应用程序激活时快速 View 重新加载

angular - PrimeNg <component> 不是已知元素错误 (@angular-2.0.0 & primeng-1.0.0-beta.16)

angular - 保护 Angular 5 应用程序免受模板中未定义数组插值的影响

arrays - 通过 json2typescript 反序列化 json 时出错

android - 上传到数据库时 Firebase 存储出错

ios - signInWithPhoneNumber() 在 react native 中不起作用