【问题标题】:Is there a better way to get a Firebase Document Reference?有没有更好的方法来获取 Firebase 文档参考?
【发布时间】:2020-03-27 22:20:33
【问题描述】:

我正在为我的 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】:
  1. ?
  2. ?
  3. 是的,我发现这是可能的!像这样:this.notes.push.apply(this.notes, newNotes);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-14
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多