简体   繁体   English

Angularfire2,startAfter() 不适用于分页

[英]Angularfire2, startAfter() not working for pagination

According to the firebase docs, this is how to do it:根据firebase docs,这是如何做到的:

var first = db.collection("cities")
        .orderBy("population")
        .limit(25);

return first.get().then(function (documentSnapshots) {
  // Get the last visible document
  var lastVisible = documentSnapshots.docs[documentSnapshots.docs.length-1];
  console.log("last", lastVisible);

  // Construct a new query starting at this document,
  // get the next 25 cities.
  var next = db.collection("cities")
          .orderBy("population")
          .startAfter(lastVisible)
          .limit(25);
});

But the problem is that I see no way of using the get function or even using snapshotChanges() to get the length then minus it to be used as a reference for the next get.但问题是我看不到使用 get 函数甚至使用snapshotChanges()来获取长度然后减去它以用作下一次获取的参考的方法。 Any tips would be greatly appreciated!任何提示将非常感谢!

Update:更新:

I tried manually inputting the index but to no avail as it returned an array with no data.我尝试手动输入索引但无济于事,因为它返回了一个没有数据的数组。

   getNewsCollectionNext() {
    this.newsCollectionRef = this.afDB.collection('news', ref => 
    ref.where('news_is_deleted', '==', false).orderBy('news_timestamp_post_created', 'desc')
    .startAfter(1));
    this.newsCollection = this.newsCollectionRef.snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data() as News;
        const id = a.payload.doc.id;
        return { id, ...data };
      }))
    );
    return this.newsCollection;
   }

While this one returns 3 items虽然这个返回 3 个项目

   getNewsCollection() {
    this.newsCollectionRef = this.afDB.collection('news', ref => 
    ref.where('news_is_deleted', '==', false).orderBy('news_timestamp_post_created', 'desc'));
    this.newsCollection = this.newsCollectionRef.snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data() as News;
        const id = a.payload.doc.id;
        return { id, ...data };
      }))
    );
    return this.newsCollection;
    // console.log(this.newsList);
   }

Update 2: I made the 'next' function work!更新 2:我使“下一个”功能起作用了!

tl;dr: So what I did was to unwrap the doc payload and changed my observable type to any to prevent conflicts :) So here's my code in the service tl; dr:所以我所做的是解开文档有效负载并将我的可观察类型更改为 any 以防止冲突:) 所以这是我在服务中的代码

  getNewsCollection() {
    this.newsCollectionSubscription = this.newsService.getNewsCollection().
    subscribe(newsCollection => {
      this.newsCollection = newsCollection;
      console.log('t2est',newsCollection[newsCollection.length - 1].doc);
      if(newsCollection){
        this.snapshot = newsCollection[newsCollection.length - 1].doc;
      }

    });
  }
  getNextNewsCollection() {
    this.newsCollectionSubscription = this.newsService.getNextNewsCollection(this.snapshot).
    subscribe(newsCollection => {
      this.newsCollection = newsCollection;
      // console.log('t2est',newsCollection[1].doc);
      console.log(newsCollection);
    });
  }

On my news-card.component.ts在我的 news-card.component.ts 上

  getNewsCollection() {
    this.newsCollectionSubscription = this.newsService.getNewsCollection().
    subscribe(newsCollection => {
      this.newsCollection = newsCollection;
      console.log('t2est',newsCollection[newsCollection.length - 1].doc);
      if(newsCollection){
        this.snapshot = newsCollection[newsCollection.length - 1].doc;
      }

    });
  }
  getNextNewsCollection() {
    this.newsCollectionSubscription = this.newsService.getNextNewsCollection(this.snapshot).
    subscribe(newsCollection => {
      this.newsCollection = newsCollection;
      // console.log('t2est',newsCollection[1].doc);
      console.log(newsCollection);
    });
  }

Have a look at the the following HTML page that shows (in pure Javascript) how to modify the query in order to display the documents page by page.查看以下 HTML 页面,该页面显示(在纯 Javascript 中)如何修改query以逐页显示文档。

You can download it to a local folder/directory, adapt the config object and open it with a browser.您可以将其下载到本地文件夹/目录,调整配置对象并使用浏览器打开它。 Clicking on the button will display, in the Console, the documents 3 by 3.单击该按钮将在控制台中显示 3 x 3 的文档。

Note that, in this simple POC, there is no error handling when the pagination reaches the end of the collection.请注意,在这个简单的 POC 中,当分页到达集合末尾时没有错误处理。

<html>
    <head>
        <script src="https://www.gstatic.com/firebasejs/5.5.3/firebase-app.js"></script>
        <script src="https://www.gstatic.com/firebasejs/5.5.3/firebase-firestore.js"></script>
    </head>

    <body>
        <button id="myBtn">Display next subset</button>

        <script>
            document.getElementById("myBtn").addEventListener("click", function () {
                displayNextPaginationSubset();
            });
          // Initialize Firebase
          var config = {
            apiKey: "....",
            authDomain: "....",
            databaseURL: "....",
            projectId: "...."
          };
          firebase.initializeApp(config);

          var db = firebase.firestore();
          var query = db.collection("cities")
              .orderBy("population")
              .limit(3);

          function displayNextPaginationSubset() {

              query.get().then(function (documentSnapshots) {

                  documentSnapshots.forEach(function(doc) {
                      // doc.data() is never undefined for query doc snapshots
                      console.log(doc.id, " => ", doc.data());
                  });


                  // Get the last visible document
                  var lastVisible = documentSnapshots.docs[documentSnapshots.docs.length-1];
                  console.log("last", lastVisible);

                  // Construct a new query starting at this document,
                  // get the next 3 cities.
                  query = db.collection("cities")
                          .orderBy("population")
                          .startAfter(lastVisible)
                          .limit(3);
              });

          }

        </script>

    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM