How to keep number from a Firestore Query in a var

2019-07-25 16:45发布

I would like to keep the number I am querying from a document in a collection in firestore and save that number in a local variable in an angular component to use it within other methods in that component.

I already tried to implement the solution provided by Ittu, but that did not work for me, since I did not understood where to use Promise.all

this is my code:

var magNum: number;

docRef.ref.get().then(
  function(doc) {
  console.log("Document data:", doc.get('painPoint'));
  magNum = doc.get('painPoint');
});

console.log('number \n' + magNum);

The result in the console is undefined, except if I put it into the function like:

var magNum: number;

docRef.ref.get().then(
  function(doc) {
  console.log("Document data:", doc.get('painPoint'));
  magNum = doc.get('painPoint');
  console.log('number \n' + magNum);
});

then magNum will be 3 in the console

1条回答
We Are One
2楼-- · 2019-07-25 17:29

You have to learn something about callback functions and promises.

Look at your code:

var magNum: number;

docRef.ref.get().then(
  function(doc) {
  console.log("Document data:", doc.get('painPoint'));
  magNum = doc.get('painPoint');
});

console.log('number \n' + magNum);

The code flow looks like the following:

  1. You declare a variable magNum as number
  2. You say: "get the document from firestore and if you done, THEN store the painPoint number to the magNum variable"
  3. Print out my magNum from firestore.

But what really happens is this:

  1. The code declares a new variable magNum as number
  2. The code starts to get your document from firestore ASYNC
  3. The code prints out your magNum (Which is undefined, because getting the firestore document isn't done yet)
  4. After some times the document is loaded and your variable magNum will be set to the value of painPoint.

Consolusion: console.log('number \n' + magNum); will be called before the line magNum = doc.get('painPoint'); and this is why magNum is undefined in console!

You can use async/await:

async yourFunction(...){
    var magNum: number;

    var doc = await docRef.ref.get();
    magNum = doc.get('painPoint');

    console.log('number \n' + magNum); // output is the value of painPoint
}
查看更多
登录 后发表回答