Angularfire2,获取数据库中数字的平均值
我已经想了好几天了。我觉得这比我想象的要简单得多。我使用angularfire2和angularfire2,我建立了一个评级系统,基本上我要做的是查询集合,获取每个文档中的数字字段,将它们相加,得到平均值。然而,我所知道的只是查询数据库,在模板中显示我的所有评论,以及如何获取集合中的文档总数,这样我就有了要除以的数字。我无法在我的typscript文件中找到如何获取所有这些值并将它们相加,然后获取和平均值Angularfire2,获取数据库中数字的平均值,angular,firebase,google-cloud-firestore,angularfire2,Angular,Firebase,Google Cloud Firestore,Angularfire2,我已经想了好几天了。我觉得这比我想象的要简单得多。我使用angularfire2和angularfire2,我建立了一个评级系统,基本上我要做的是查询集合,获取每个文档中的数字字段,将它们相加,得到平均值。然而,我所知道的只是查询数据库,在模板中显示我的所有评论,以及如何获取集合中的文档总数,这样我就有了要除以的数字。我无法在我的typscript文件中找到如何获取所有这些值并将它们相加,然后获取和平均值 this.reviews = db.collection('dispensaries').
this.reviews = db.collection('dispensaries').doc(this.id).collection('reviews').snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data();
data.id = a.payload.doc.id;
console.log(data.stars);
return data;
});
});
db.collection('dispensaries').doc(this.id).collection('reviews')
.ref
.get().then(function(querySnapshot) {
console.log(querySnapshot.size);
});
我遇到了类似的问题,但我能够获得数据并将数字放入变量中,问题是我无法在firestore内部执行更新,但我附加了一个可能适用于您的代码,此方法需要2个参数:id和一个必须添加到现有参数中的数字(金额),我用get方法得到的现有的一个 代码: } 按照构造函数中的逻辑,我将afs声明为angularfirestore
constructor(public afs: AngularFirestore) {
我现在找到的解决方案是:
在服役中
agregaCantidad(id, cant){
this.afs.doc(`productos/${id}`).ref.get().then(function(doc) {
if (doc.exists) {
const reemplazarCantidad = doc.get('cantidadActual') + cant;
doc.ref.update({cantidadActual: reemplazarCantidad});
} else {
console.log('No hay datos');
}
}).catch(function(error) {
console.log('Error:', error);
});
}
并调用该方法:
this.xxservicexx.agregaCantidad(idProducto,cantidad)
注意:此解决方案的一部分涉及将产品本身的名称记录为产品id。在我看来,这是最实际的
但我不确定这是对的还是最好的
谢谢,并致以最良好的问候。
毫升
agregaCantidad(id, cant){
this.afs.doc(`productos/${id}`).ref.get().then(function(doc) {
if (doc.exists) {
const reemplazarCantidad = doc.get('cantidadActual') + cant;
doc.ref.update({cantidadActual: reemplazarCantidad});
} else {
console.log('No hay datos');
}
}).catch(function(error) {
console.log('Error:', error);
});