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
You have to learn something about callback functions and promises.
Look at your code:
The code flow looks like the following:
magNum
as numberpainPoint
number to themagNum
variable"magNum
from firestore.But what really happens is this:
magNum
as numbermagNum
(Which is undefined, because getting the firestore document isn't done yet)magNum
will be set to the value ofpainPoint
.Consolusion:
console.log('number \n' + magNum);
will be called before the linemagNum = doc.get('painPoint');
and this is whymagNum
isundefined
in console!You can use async/await: