简体   繁体   中英

How would I set up a loop to pull records from a firebase database using Typescript

How would I set up a loop to pull only 10 records, then it would pull a different 10 records from a firebase database using Typescript.

I have a function that returns the first 10 however, now I want to grab the next 10

his.dataProvider.getProducts().subscribe((products) => {
      this.products = products;

  //Pull an Array of ASINs from Firebase Database
  this.products.forEach(product => {
  this.asins.push(product.ASIN)

  this.productKey.push(product.$key)
  //console.log(this.productKey.toString());
  var lastASIN = this.productKey.pop();
  console.log (lastASIN);

    return this.dataProvider.getNextProducts(lastASIN).subscribe((products) => {
      this.products.forEach(product => {
        this.asins.push(product.ASIN)
        this.productKey.push(product.$key)
        var newASIN = this.productKey.pop();
        console.log (newASIN);
      })
    })

  });

Since you are dealing with observables, you can use skip and take .

import 'rxjs/add/operator/take';
import 'rxjs/add/operator/skip';

You can use them like this:

this.dataProvider.getNextProducts(lastASIN).skip(numToSkip).take(10).subscribe(...

Just keep track of how many records you need to skip with numToSkip and specify how many records you want to take and you should be good.

Edit

Since your trying to do infinite scrolling, I would not use skip and take from rxjs. I've not used the firebase api, but after taking a quick look at it, I would modify your firebase query to use the startAt() and limitToFirst() Firebase JS SDK functions. There is a good example here . And the docs are here . But the gist is this:

new Firebase("https://examples-sql-queries.firebaseio.com/widget")
   .startAt(null, lastWidgetOnPrevPage)
   .limitToFirst(LIMIT+1) // add one to limit to account for lastWidgetOnPrevPage
   .once('value', function(snap) {
      var vals = snap.val()||{};
      delete vals[lastWidgetOnPrevPage]; // delete the extraneous record
      console.log('widgets on this page', vals);
   });

Use startAt() to query for values at or beyond the value provided. Use limitToFirst(10) to grab the first x number of values starting at the startAt() value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM