Extract data from FirebaseListObservable to Array

2019-07-17 09:30发布

问题:

sorry for my english, i have this observable:

this.productos = af.database.list('/productos', {
    query: {
      orderByChild: 'categoria',
      equalTo: this.catnombre
    }
    });

I need extract all id from here and set in a array but i dont know how, thanks.

Edit:

I can extract the id but I use de key, now i need extract other data, but snapshot.val, dont work.

  this.productos = af.database.list('/productos/', {
    query: {
      orderByChild: 'categoria',
      equalTo: this.catnombre
    }, preserveSnapshot:true
    });

    this.productos.subscribe(snapshot => {

         snapshot.forEach(snapshot => {

           console.log(snapshot.key);
           this.idproductos.push(snapshot.key); 

         });
         console.log(this.idproductos);
    });

回答1:

All you need to do is

this.productos = af.database.list('/productos/', {
    query: {
      orderByChild: 'categoria',
      equalTo: this.catnombre
    })
  .map(products => products.map(product => product.$key));

The result will be an observable of arrays of keys. Now you can subscribe it to or do whatever else you want to.

this.productos.subscribe(keys => console.log("keys are", keys));

If AngularFire, and things like FirebaseListObservable, are used correctly, you don't need to worry about snapshots, or taking their val(), or doing forEach on them, or taking elements and putting them onto your own array. The FirebaseListObservable is an observable of arrays. Simply map it to create other observables, as we have done above to create an observable of arrays of keys, or subscribe to it to get the underlying data.