FIREBASE 获取文档数据

FIREBASE getting document data

我正在制作一个应用程序并尝试通过它在 ionic 4 中的模态内的 id 获取产品数据。 我正在使用打字稿来做,但没有运气。 因为对 firebase 的 de 调用是异步的,所以我无法获取保存在 firebase 中的数据,而且因为我是新手,所以我无法找到编写代码的正确方法。 我读到了如何做到这一点,但我很难实现它。

这是我尝试从 firebase 获取产品数据的函数。 它总是在 console.log('todo', todo).

上记录为空
async editProduct(id) {
        const getTodo = docRef => {
            setTimeout(() => {
                docRef = this.afs.collection("products").doc(id);
                docRef.get().subscribe((doc) => {
                    if (doc.exists) {
                        let data = doc.data();
                        return data;
                    } else {
                        console.log("No document.");
                        return false;
                    }
                });
            }, 2000)
        }

        getTodo(todo => {
            console.log('todo', todo)
        })

        const modal = await this.modalCtrl.create({
            component: AdminProductPage,
            'id': id,
        });
        await modal.present();
    }

您的“getTodo”有问题。可能你正在用你的代码记录空数据,我可以给你正确的功能示例:

myData

editProduct() {
    this.afs.collection("products").doc(id)
        .valueChanges()
        .subscribe(data => {
          console.log(data)
          myData = data
        })
}

getData() {
    console.log(this.myData) // You will log it twice with this line
}

GOOGLE 示例

docRef.get().then((doc) => {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch((error) => {
    console.log("Error getting document:", error);
});

https://firebase.google.com/docs/firestore/query-data/get-data?hl=es