如何将Firestore查询中的数字保留在变量中以备将来使用? [英] How to keep number from a Firestore Query in a variable for further usage?
问题描述
我想将要从文档中查询的数字保留在firestore的集合中,并将该数字保存在有角度的组件的局部变量中,以便在该组件的其他方法中使用.
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.
我已经尝试实施Ittu提供的解决方案,但这对我不起作用,因为我没有这样做了解在何处使用 Promise.all
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
这是我的代码:
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);
在控制台中的结果为 undefined
,除非我将其放入以下函数中:
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);
});
然后控制台中的magNum为3
then magNum will be 3 in the console
推荐答案
您必须学习有关回调函数和promise的知识.
You have to learn something about callback functions and promises.
查看您的代码:
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);
代码流如下所示:
- 您将变量
magNum
声明为数字 - 您说:从firestore中获取文档,如果完成,则将
painPoint
号存储到magNum
变量中" - 从firestore中打印出我的
magNum
.
- You declare a variable
magNum
as number - You say: "get the document from firestore and if you done, THEN store the
painPoint
number to themagNum
variable" - Print out my
magNum
from firestore.
但是真正发生的是这件事
But what really happens is this:
- 代码将新变量
magNum
声明为数字 - 代码开始从Firestore ASYNC 获取您的文档
- 该代码会打印出您的
magNum
(未定义,因为尚未完成Firestore文档的获取) - 加载文档后,变量
magNum
将设置为painPoint
的值.
- The code declares a new variable
magNum
as number - The code starts to get your document from firestore ASYNC
- The code prints out your
magNum
(Which is undefined, because getting the firestore document isn't done yet) - After some times the document is loaded and your variable
magNum
will be set to the value ofpainPoint
.
安慰: console.log('number \ n'+ magNum);
将在 magNum = doc.get('painPoint');
,这就是为什么控制台中 magNum
未定义
的原因!
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!
您可以使用 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
}
这篇关于如何将Firestore查询中的数字保留在变量中以备将来使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!