I’m making an app and trying to get product data by it’s id inside a modal in ionic 4. I’m using typescript to do it but without luck. Because de calls to firebase are asynchronous i cannot get the data that is held in firebase and also because i’m new to subject i cannot figured out the proper way to write the code. I read about how to do it but i’m having a hard time to achieve it.
Here is my function that tries to grab product data from firebase. It always logs empty on console.log(‘todo’, todo).
JavaScript
x
27
27
1
async editProduct(id) {
2
const getTodo = docRef => {
3
setTimeout(() => {
4
docRef = this.afs.collection("products").doc(id);
5
docRef.get().subscribe((doc) => {
6
if (doc.exists) {
7
let data = doc.data();
8
return data;
9
} else {
10
console.log("No document.");
11
return false;
12
}
13
});
14
}, 2000)
15
}
16
17
getTodo(todo => {
18
console.log('todo', todo)
19
})
20
21
const modal = await this.modalCtrl.create({
22
component: AdminProductPage,
23
'id': id,
24
});
25
await modal.present();
26
}
27
Advertisement
Answer
There is something wrong with your “getTodo”. Probable you are logging empty data with your code, I can give you the proper functional example:
JavaScript
1
15
15
1
myData
2
3
editProduct() {
4
this.afs.collection("products").doc(id)
5
.valueChanges()
6
.subscribe(data => {
7
console.log(data)
8
myData = data
9
})
10
}
11
12
getData() {
13
console.log(this.myData) // You will log it twice with this line
14
}
15
GOOGLE EXAMPLE
JavaScript
1
11
11
1
docRef.get().then((doc) => {
2
if (doc.exists) {
3
console.log("Document data:", doc.data());
4
} else {
5
// doc.data() will be undefined in this case
6
console.log("No such document!");
7
}
8
}).catch((error) => {
9
console.log("Error getting document:", error);
10
});
11
https://firebase.google.com/docs/firestore/query-data/get-data?hl=es