分页可观察数组

dmu*_*rer 3 arrays observable angular google-cloud-firestore

我想显示从 Firestore 获取的文档列表。我想默认显示 5 个文档并显示一个“加载更多”按钮,单击该按钮将获取另外 5 个文档。

使用静态列表,我会这样做,相当简单:

loadMoreInvoices() {
  //Get number of last item
  var lastItemInvoiceNumber = (this.invoices[this.invoices.length-1] as any).invoice_number;

  this.afs.collection('clients').doc(uid).collection('invoices', ref => ref.orderBy('invoice_number').startAt(lastItemInvoiceNumber).limit(5+1)).get().then(snap => {

    //Remove first elem from array as it is a duplicate
    snap.shift()
    //Add all loaded invoices to array
    snap.forEach(item => {
      this.invoices.push(item)
    })

    //Check if there are any more invoices to be loaded and set status accordingly
    if (snap.length < this.moreInvoicesToBeLoaded) {
      this.noMoreInvoices = true;
    } else {
      this.noMoreInvoices = false;
    }
  });
}

ngOnInit() {
    this.afs.collection('clients').doc(uid).collection('invoices', ref => ref.orderBy('invoice_number').limit(invoicesToBeLoaded)).get().then(snap => {
        if (invoices.length < this.invoicesToBeLoaded) {
            //Display "Load more" only if false
            this.noMoreInvoices = true;
        }
        this.invoices = invoices;
        this.loaded = true;
    })
}
Run Code Online (Sandbox Code Playgroud)

如何使用 Observables 而不是静态数据获得相同的行为?this.invoices由于 Observable 的变化,我上面的方法会导致列表损坏。

Ser*_*gey 5

scan操作符的帮助下可以逐步添加一些信息,该操作符允许您使用累加器并返回一个新值,该值将传递给消费者,并将作为下一次可观察发射的累加器。

你可以做这样的事情

source$ = this.page$.pipe(
  switchMap(page => this.getList(page)),
  // here the magic goes. We initialize scan with "[]" seed (otherwise only second
  // emit will be passed further as first one would be taken for the seed for accumulator)
  // and use concat which returns new array of concatenated "acc" and "vall"
  scan((acc, val) => acc.concat(val), [])
)
Run Code Online (Sandbox Code Playgroud)

然后您只需source$ | async在模板中使用,您就可以增量地获取和更新数据(又名无限滚动)。

this.page$ 是用于分页以对远程资源进行新调用的 observable。