Search code examples
angulargoogle-cloud-firestoreangularfire

How to assign value to variable in angular subscribe method


I have a service that will use angularfire to get data from firestore. Once i get the data i wish to assign the value to a global variable like this.currentQuantity. But the value for this.currentQuantity is getting undefine outside the subscribe() method while getting correct within the subscribe method.

my component.ts file

onBuy(){
 this.stockService.GetOverviewStock().subscribe((response) => {
      response.forEach((item) => {
        if (item.StockName == this.selectedStockName) {
          this.currentQuantity = item.Quantity;
          this.currentTotalMoneySpent = item.TotalMoneySpent;
        }
        console.log(this.currentQuantity) // correct value from firestore
      });
    });

 console.log(this.currentQuantity) // undefine
...doSomething(this.currentQuantity) // the value is undefine
}
   
   

My service.ts file that get data from firestore.

  GetOverviewStock() {
    return this.firestore
      .collection<StockModel>("OverviewStock", (ref) => ref.orderBy("StockName", "asc"))
      .valueChanges();
  }

Help, I am new to angular and do not really understand why and how to solve.


Solution

  • Observables are new way of handling async requests. Subscriptions to Observables are quite similar to calling a function. But where Observables are different is in their ability to return multiple values called streams.Observables not only able to return a value synchronously, but also asynchronously.

    In your case first the second console.log(this.currentQuantity) is executed which is not initialized with the subscription and because of that you get undefine first and then your subscription evaluated. You can try this:

    app.component.ts

    ngOnInit() {
      this.stockService.GetOverviewStock().subscribe((response) => {
          response.forEach((item) => {
            if (item.StockName == this.selectedStockName) {
              this.currentQuantity = item.Quantity;
              this.currentTotalMoneySpent = item.TotalMoneySpent;
            }
            console.log(this.currentQuantity) // correct value from firestore
            this.logObservable();
          });
      });
    }
    
    logObservable() {
      console.log(this.currentQuantity)
    }
    
    

    Here this.logObservable() is out of the subscription and if you check it the answer is correct. So you should consider the async behavior and do something like this.