是否有更好的方法来获取Firebase文档参考?

问题描述 投票:0回答:1

我正在为我的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. 是否可以对post属性使用类似.push()之类的东西?
  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()
        }
      }))
    })
  }
javascript angular firebase google-cloud-firestore angularfire
1个回答
0
投票
  1. 是的,我发现这是可能的!像这样:

loadOtherNotes(a){this.firestore.collection('note',ref => ref.orderBy('createdAt','desc')。startAfter(this.lastNote).limit(this.itemsPerPage))。snapshotChanges()。pipe(take(1 ))。subscribe(actionArray => {console.log(this.notes);让newNotes = actionArray.map(item => {返回{... item.payload.doc.data()}})

  // add new notes to exits notes + refresh lastNote reference
  this.notes.push.apply(this.notes, newNotes);
  this.lastNote = actionArray[actionArray.length-1].payload.doc;
})

}

© www.soinside.com 2019 - 2024. All rights reserved.