0

I have a function that gets a product from my firstore database with the id. when i console.log the array in the subscribe i get :

console.log(product[0]) -> Object { id: 0, quantity: 1, latinName: "stub", price: "10", name: "foo", }
console.log(product) -> [{ id: 0, quantity: 1, latinName: "stub", price: "10", name: "foo", }]

that's good and normal but when i do a console.log outside the subscribe. Where i want to return the array i get different values. then i get :

console.log(product[0]) -> undefined
console.log(product) -> [{ id: 0, quantity: 1, latinName: "stub", price: "10", name: "foo", }]

This is my code for getting the data and returning it

   getProductfromDBByID(id: number): Observable<any> {
    let product: Array<any> = [];
    this.firestore
      .collection('products', (ref) => ref.where('id', '==', id))
      .get()
      .subscribe((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          product.push(doc.data());
          console.log('product in subscribe ', product[0]);
        });
      });
    console.log('product return value', product[0]);
    return of(product);
  }
R. Richards
  • 24,603
  • 10
  • 64
  • 64
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – takendarkk Jan 27 '21 at 20:17

2 Answers2

0

That is because the console.log outside of the subscribe is executed before the subscribe is hit (asynchronous operation, request in this case).

To resolve that, move the actual subscription to the function that calls this function.

getProductfromDBByID(id: number): Observable<any> {
  return this.firestore
    .collection('products', (ref) => ref.where('id', '==', id))
    .get();
}

...

product: Array<any>;

otherFunction() {
  getProductfromDBByID(/*some id*/)
    .subscribe((querySnapshot) => {
      querySnapshot.forEach((doc) => {
        this.product.push(doc.data());
      });
    });
}
Gunnar B.
  • 2,879
  • 2
  • 11
  • 17
0

Add "async" keyword before the function name and add "await" keyword before the future method which is the "this.firestore......"

async getProductfromDBByID(id: number): Observable<any> {
    let product: Array<any> = [];
    await this.firestore
      .collection('products', (ref) => ref.where('id', '==', id))
      .get()
      .subscribe((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          product.push(doc.data());
          console.log('product in subscribe ', product[0]);
        });
      });
    console.log('product return value', product[0]);
    return of(product);
  }
Ibrahim Ali
  • 2,083
  • 2
  • 15
  • 36