【问题标题】:How to get data from firestore DB in outside of onSnapshot如何从 onSnapshot 之外的 Firestore DB 获取数据
【发布时间】:2019-02-28 11:34:12
【问题描述】:

当我尝试从 firestore 获取值并将其放入变量时结果未定义,但在控制台中有效。

我的代码:

this.db.collection('Users').doc(uid).get()
  .then((docSnapshot) => {
    if (docSnapshot.exists) {
      this.db.collection('Users').doc(uid)
        .onSnapshot((doc) => {
          console.log(doc.data()); //working
          perfil = doc.data(); //not working
        });
    }
  });

console.log(perfil); //not working. Display undefined

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    数据从 Cloud Firestore 异步加载。因为这可能需要一些时间,所以回调之后的代码会立即继续。然后当数据可用时,Firestore 会调用您的 onSnapshot 回调。

    通过添加一些日志语句最容易看到发生了什么:

    console.log('Before adding listener');
    this.db.collection('Users').doc(uid).get()
    .then((docSnapshot) =>{
      console.log('Got data');
    });
    console.log('After adding listener');
    

    当你运行这段代码时,它会打印:

    添加监听器之前

    添加监听器后

    得到数据

    这可能不是您期望的顺序。但它完美地解释了为什么您的console.log(perfil) 打印undefined:数据尚未加载!

    因此,所有需要访问数据的代码都需要在onSnapshot 回调中。例如:

    this.db.collection('Users').doc(uid).get()
    .then((docSnapshot) =>{
      if (docSnapshot.exists) {
        this.db.collection('Users').doc(uid)
        .onSnapshot((doc) => {
            console.log(doc.data());
            perfil = doc.data();
            console.log(perfil);
        });
      }
    });
    

    有关更多信息,请参阅:

    【讨论】:

      猜你喜欢
      • 2022-06-11
      • 2021-09-29
      • 2021-11-26
      • 2020-01-25
      • 2020-03-17
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 2020-06-03
      相关资源
      最近更新 更多