首页 > 解决方案 > AngularFirestore - 限制和启动后不工作

问题描述

我正在尝试构建一个网页AngularFireStore作为我的数据存储。为了启用无限滚动,我正在limit尝试startAfter使用AngularFireStore.

出于某种原因,我无法让它工作。该limit功能未按预期工作,因为它返回的值大于/小于实际限制,并且还有重复值

我已经搜索并尝试了几种方法(thisthisthis)。但没有任何效果。

这是我尝试过的:

crudService.ts :

readNextPost(cursor){
    return this.firestore.collection('MyCollection',
                                      ref => ref.orderBy('date', 'desc')
                                                .startAfter(cursor)
                                                .limit(10)
                                                ).snapshotChanges();
  }

组件.ts

mapResponseToObject(data) {
  return {
    id: data.payload.doc.id,
    doc: data.payload.doc
  }
}

setLastPost(data) {
  this.lastFetchedPost = data[data.length - 1].doc;
}

fetchNextPosts() {
    this.crudService.readNextPost(this.lastFetchedPost).subscribe(data =>{
      let nextPost = data.map(this.mapResponseToObject)
      this.allPosts = [...this.allPosts, ...nextPost];
      this.setLastPost(nextPost);
    })
  }

readNextPost返回的值小于,10尽管存储中的值大于,有时返回的值大于10,其中的值是较早获取的。这会导致网页中出现重复数据。

作为 和 的新手AngularFireStoreAngular 10我在这个问题上停留了几个小时。任何帮助将非常感激。非常感谢。

标签: javascriptangularfirebasegoogle-cloud-firestoreangularfire2

解决方案


尝试订阅:

  this.firestore.collection('MyCollection',
                                  ref => ref.orderBy('date', 'desc')
                                            .startAfter(cursor)
                                            .limit(10)
                                            ).get()
                       .subscribe(response => {
                        for (const item of response.docs) {
                            console.log(item.data());
                          }
                    });;

我认为 snapshotChanges 是“更改”流,而不是查询的完整结果。我假设这意味着查询结果的更改,但文档不太清楚:

https://github.com/angular/angularfire/blob/master/docs/firestore/collections.md#snapshotchanges


推荐阅读