Angularfire2,startAfter()无法用于分页 [英] Angularfire2, startAfter() not working for pagination

查看:62
本文介绍了Angularfire2,startAfter()无法用于分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据firebase文档,这是这样做的方法:

According to the firebase docs, this is how to do it:

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);
});

但是问题是我看不到使用get函数,甚至无法使用 snapshotChanges()来获取长度然后减去它来用作下一次get的参考的方法.任何提示将不胜感激!

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. Any tips would be greatly appreciated!

更新:

我尝试手动输入索引,但无济于事,因为它返回了一个没有数据的数组.

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;
   }

虽然这将返回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);
   }

更新2:我使下一个"功能正常工作!

Update 2: I made the 'next' function work!

tl; dr:所以我要做的是解开文档有效负载并将我的可观察类型更改为任何可防止冲突的类型:)所以这是我在服务中的代码

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

  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);
    });
  }

在我的news-card.component.ts

On my 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);
    });
  }

推荐答案

看看下面的HTML页面,该页面以纯Javascript显示了如何修改 query 以显示文档逐页显示.

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.

您可以将其下载到本地文件夹/目录,调整配置对象并使用浏览器将其打开.单击该按钮将在控制台中显示3比3的文档.

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.

请注意,在这个简单的POC中,当分页到达集合的末尾时,没有错误处理.

Note that, in this simple POC, there is no error handling when the pagination reaches the end of the collection.

<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>

这篇关于Angularfire2,startAfter()无法用于分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆