Home > Blockchain >  How to get a variable from angularfire, even though it is an observable?
How to get a variable from angularfire, even though it is an observable?

Time:08-16

So, I don't know anything about angular much less how to select a specific field from my DB as it comes in Observable. Tried everywhere to see an example but to no avail.

I'm using angular firebase, with the angularFire library. There are examples in the documentation that I couldn't adapt.

This is my code made by following it.

constructor( private aff: AngularFirestore, public crud: CrudService ) { 
this.prodCollection = aff.collection<Product>('prods');
this.prods = this.prodCollection.snapshotChanges().pipe(
  map(actions => actions.map(a => {
    const data = a.payload.doc.data() as Product;
    return { ...data };
  }))
);
console.log(this.prods);
}

[This is a message you receive on the console.1

I need to get only one "variable", how can I do that? With data=> res => or any recommended

CodePudding user response:

You need to subscribe to it.

this.prodCollection.snapshotChanges()
  .pipe(
    map(actions => actions.map(a => {
      const data = a.payload.doc.data() as Product;
      return { ...data };
    }))
 )
 .subscribe((data) => this.prods = data); // YMMV 

CodePudding user response:

as Matthieu Riegler told you need to subscribe. This is not angular or firebase specific.

You can do it many ways but if my understanding is correct to retrieve the variable only one time and without needing to unsubscribe you could do;

this.prodCollection.snapshotChanges()
  .pipe(
    take( 1 ) // You only retrive value once
  ).subscribe( snapshot => {

     const data = <Product[]> a.payload.doc.data();

     this.prods = data;

   } );

using the map function helps you process the data before subscription, this can help you avoiding boilerplate code if you for example share the same observable across multiple components. This way you could do:

this.prodCollection.snapshotChanges()
  .pipe(
    take( 1 ) // You only retrive value once
    map( snapshot => ( snapshot.payload.doc.data() as Product[] ) )
  ).subscribe( ( data:Product[] ) => {

     this.prods = data;

   } );
  • Related