如何在Angular(6)和Firebase Firestore设置中分页回到上一页 [英] Howto paginate back to previous pages in a Angular(6) and firebase Firestore setup

查看:98
本文介绍了如何在Angular(6)和Firebase Firestore设置中分页回到上一页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将Angular与Cloud Firestore(Firebase)结合使用时,似乎有很多示例,教程和视频,以及如何分页到下一页.

There seem to be a lot of examples, tutorials and videos on howto paginate to the next page when using Angular with Cloud Firestore (Firebase).

但是在大​​量搜索之后,我找不到分页到上一页的方法. 我得到的最远的就是返回第一页.

But after extensive search i cannot find a way to paginate to a previous page. The furthest i got is just returning to the first page.

这是我的服务现在的外观:

Here is how my Service looks right now:

import { Injectable } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Task } from './task.model';

@Injectable()
export class TaskService {
  private _data: BehaviorSubject<Task[]>;
  public data: Observable<Task[]>;
  firstEntry: any;
  latestEntry: any;

  constructor(private afs: AngularFirestore) { }

  public first() {
    this._data = new BehaviorSubject([]);
    this.data = this._data.asObservable();

    const tasksRef = this.getCollection('tasks', ref => ref.orderBy('createdAt').limit(5))
      .subscribe(data => {
        this.firstEntry = data[0].doc;
        this.latestEntry = data[data.length - 1].doc;
        this._data.next(data);
      });
  }

  public next() {
    const tasksRef = this.getCollection('tasks', ref => ref.orderBy('createdAt').startAfter(this.latestEntry).limit(5))
      .subscribe(data => {
        if (data.length) {
          this.firstEntry = data[0].doc;
          this.latestEntry = data[data.length - 1].doc;
          this._data.next(data);
        }
      });
  }

  public previous() {
    const tasksRef = this.getCollection('tasks', ref => ref.orderBy('createdAt').endBefore(this.firstEntry).limit(5))
      .subscribe(data => {
        if (data.length) {
          this.firstEntry = data[0].doc;
          this.latestEntry = data[data.length - 1].doc;
          this._data.next(data);
        }
      });
  }

  private getCollection(ref, queryFn?): Observable<any[]> {
    return this.afs.collection(ref, queryFn).snapshotChanges().pipe(
      map(actions => {
        return actions.map(a => {
          const data = a.payload.doc.data();
          const id = a.payload.doc.id;
          const doc = a.payload.doc;
          return { id, ...data, doc };
        });
      })
    );
  }
}

初始加载(第一页)有效,并且所有后续页面均按预期工作. 但是endBefore(this.firstEntry)似乎没有正确的光标,并再次显示在第一页.

The initial loading (first page) works, and also all next pages are working as expected. But it seems like endBefore(this.firstEntry) doesn't hold the correct cursor, and results in the first page again.

导航回上一页的正确方法是什么?

What is the proper way to navigate back to the previous page?

如果有人知道完整的教程或可行的分页器示例,请分享...

And if someone knows of a complete tutorial or example of a working paginator, please share...

推荐答案

import * as firebase from 'firebase/app';
import { last } from 'lodash';
import { dropRight } from 'lodash';

安装此npm软件包(Lodash,Firebase)

Install this npm packages ( Lodash, Firebase )

在导入Firebase之后,从lodash持续并放下dropRight. Last方法返回数组的最后一个元素. DropRight方法对数组的最后一个元素进行切片.

After import firebase, last and dropRight from lodash. Last method returns the last element of array. DropRight method slices the last element of the array.

allEntry: Array<any[]> =  [];
firstEntry = [];
lastEntry;

创建三个变量,并将firstEntry分配给数组,以便在查询中存储第一个数据. AllEntry存储从查询中检索到的所有数据. LastEntry将最后一个元素存储在allEntry中,该元素将用作游标来获取之后的数据.

Create three variables and assign the the firstEntry to an array in order to store the first data in the query. AllEntry stores all the data retrieved from the query. LastEntry to store the last element in the allEntry which would be used to as a cursor to get the data after that.

getMainEntry() {
return this.afs.collection('tasks', ref => ref.orderBy('createdAt').limit(5)).valueChanges().subscribe(data => {
  this.allentry = data;
  firebase.firestore().collection('tasks').doc(data[data.length - 1]['key']).onSnapshot(c => {
    this.lastentry = c;
    firebase.firestore().collection('tasks').doc(data[0]['key']).onSnapshot(da => {
      this.firstEntry.push(da);
    });
  });
});
}

此getMainEntry函数获取集合中的数据,按createdAt对其进行排序,并将其限制为5.然后获取allEntry数组中最后一个元素的documentsnapshot并将其分配给lastEntry.之后,将allEntry数组中第一个元素的documentsnapshot推送到firstEntry数组中.

This getMainEntry function gets the data in the collection, orders it by createdAt and limits it to 5. Then gets and assigns the documentsnapshot of the last element in the allEntry array to the lastEntry. After gets and pushes the documentsnapshot of the first element in the allEntry array into the firstEntry array.

现在让我们创建下一个函数

Now let's create the next function

getNextData(){
  const entarr = [];
  firebase.firestore().collection('tasks').orderBy('createdAt').startAfter(this.lastEntry).limit(5).get().then((data) => {
    data.docs.map(a => {
      entarr.push(a.data());
      this.allEntry = entarr;
    });
  }).then(() => {
    firebase.firestore().collection('tasks').doc(entarr[entarr.length - 1]['key']).onSnapshot(data => {
      this.lastEntry = data;
    });
  }).then(() => {
    firebase.firestore().collection('tasks').doc(entarr[0]['key']).onSnapshot(da => {
      this.firstEntry.push(da);
    });
  });
}

getNextData函数获取集合中的下一个数据,按createdAt对其进行排序,并将其限制为lastEntry之后的下5个数据.然后获取并将entarr数组中最后一个元素的documentsnapshot分配给lastEntry.之后,将allEntry数组中第一个元素的documentsnapshot推送到firstEntry数组中.

The getNextData function gets the next data in the collection, orders it by createdAt and limits it to the next 5 data after the lastEntry. Then gets and assigns the documentsnapshot of the last element in the entarr array to the lastEntry. After gets and pushes the documentsnapshot of the first element in the allEntry array into the firstEntry array.

上一个功能

getPrevData() {
const entarr = [];
  this.firstEntry = dropRight(this.firstEntry);
const firstEntry = last(this.firstEntry);
firebase.firestore().collection('tasks').orderBy('createdAt').startAt(firstEntry).limit(5).get().then((d) => {
  d.docs.map(a => {
    entarr.push(a.data());
    this.allEntry = entarr;
    });
  }).then(() => {
    firebase.firestore().collection('tasks').doc(entarr[entarr.length - 1]['key']).onSnapshot(da => {
      this.lastEntry = da;
    });
  });
}

希望这会很有用.

这篇关于如何在Angular(6)和Firebase Firestore设置中分页回到上一页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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