Firestore + AngularFire2 pagination ( query items by range - .startAfter(lastVisible) )

后端 未结 3 445
借酒劲吻你
借酒劲吻你 2020-12-09 13:56

In a component I want to pull a range of items from FireStore, for ex. from 0 to 5, from 5 to 10 etc. I found this in FireStore\'s docs, but they dont use AngularFire2 so as

3条回答
  •  青春惊慌失措
    2020-12-09 14:19

    I had the same Problem and this is what i did.

    Service

    private _data: BehaviorSubject;
    public data: Observable;
    latestEntry: any;
    
    constructor(private afs: AngularFirestore) {}
    
    // You need to return the doc to get the current cursor.
      getCollection(ref, queryFn?): Observable {
        return this.afs.collection(ref, queryFn).snapshotChanges().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 };
          });
        });
      }
    // In your first query you subscribe to the collection and save the latest entry
     first() {
      this._data = new BehaviorSubject([]);
      this.data = this._data.asObservable();
    
      const scoresRef = this.getCollection('scores', ref => ref
        .orderBy('score', 'desc')
        .limit(6))
        .subscribe(data => {
          this.latestEntry = data[data.length - 1].doc;
          this._data.next(data);
        });
      }
    
      next() {
        const scoresRef = this.getCollection('scores', ref => ref
          .orderBy('scores', 'desc')
           // Now you can use the latestEntry to query with startAfter
          .startAfter(this.latestEntry)
          .limit(6))
          .subscribe(data => {
            if (data.length) {
              // And save it again for more queries
              this.latestEntry = data[data.length - 1].doc;
              this._data.next(data);
            }
          });
      }
    

    Component

      scores$: Observable;
      ...
      ngOnInit() {
        this.yourService.first();
        this.scores$ = this.yourService.data;
      }
    
      nextPage() {
       this.yourService.next();
      }
    

提交回复
热议问题