gpt4 book ai didi

arrays - 对可观察数组进行分页

转载 作者:行者123 更新时间:2023-12-02 07:04:26 24 4
gpt4 key购买 nike

我想显示从 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;
})
}

如何使用 Observables 而不是静态数据获得相同的行为?我上面的做法会导致 this.invoices 由于 Observable 发生更改后列表损坏。

最佳答案

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), [])
)

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

this.page$ 是一个用于分页的可观察对象,用于对远程资源进行新的调用。

关于arrays - 对可观察数组进行分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58910964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com