0

I currently working on a mobile application using the front-end framework Ionic and angularjs with typescript and for the backend I'm using firebase. My problem is that when I make a call to my firebase nosql database I can't get it my items into an typescript array in order to get the data to the screen because when I call the variable containing the values it comes as undefined. Here is my code:

getSingleDatabase(){
this.collectionReference=this.db.collection('posts');
      this.collectionReference.get()
  .then(snapshot =>{
  snapshot.forEach(doc => {

    this.firstGet.push(doc.data());
  });
})
.catch(err =>{
  console.log(err);
});
return this.firstGet;

}

1 Answer 1

1

Firstore APIs are asynchronous, meaning your call to get() returns immediately with a promise that indicates when the fetch is actually complete. It could take any amount of time until the promise is fulfilled with the document you're looking for. As a result, your getSingleDatabase function is going to return before the data is available in this.firstGet. You will be able to see what I mean if you put logging statements at every stage in your code.

The only way to know when the data is fully available is to use the promise returned by get(), which means you should not be expecting this.firstGet to contain anything until the promise is fulfilled.

Please read more about why Firebase APIs are asynchronous and what to expect from them.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.