首页 > 解决方案 > 有没有更好的方法来获取 Firebase 文档参考?

问题描述

我正在为我的 Firebase 应用程序构建分页。我正在使用 Angular 和 AngularFire 库。我正在尝试获取DocumentReference用于分页,但我的代码似乎有点奇怪。也许您知道获取文档参考的更好解决方案?

在我的组件中:

  posts: any;
  lastPost: any;

   constructor(private afs: AngularFirestore) {
    afs.collection('posts', ref => ref.orderBy('createdAt', 'desc').limit(10)).snapshotChanges().pipe(take(1)).subscribe(actionArray => {
      this.posts = actionArray.map(item => {
        return { 
          ...item.payload.doc.data()
        }
      })

      this.lastPost = actionArray[actionArray.length-1].payload.doc; // get the docReference
    });
  }

稍后在组件中,我有另一个函数,我传递此文档引用以以此文档引用为起点加载其他帖子:

loadOtherPost() {
    this.firestore.collection('posts', ref => ref.orderBy('createdAt', 'desc').startAfter(this.lastPost).limit(10)).snapshotChanges().pipe(take(1)).subscribe(actionArray => {
      this.posts = actionArray.map(item => {
        return {
          ...item.payload.doc.data()
        }
      })
    })
  }

在视图中:

显示新消息☀

我的问题:

  1. 有更好的方法吗?我看到很多代码重复。
  2. 我需要处理取消订阅事件以避免性能下降吗?
  3. 是否可以使用类似.push()post 属性的东西?
  loadOtherPost() {
    this.firestore.collection('posts', ref => ref.orderBy('createdAt', 'desc').startAfter(this.lastPost).limit(10)).snapshotChanges().pipe(take(1)).subscribe(actionArray => {
      this.posts.push(actionArray.map(item => {
        return {
          ...item.payload.doc.data()
        }
      }))
    })
  }

标签: javascriptangularfirebasegoogle-cloud-firestoreangularfire

解决方案


  1. ?
  2. ?
  3. 是的,我发现这是可能的!像这样: this.notes.push.apply(this.notes, newNotes);

推荐阅读