angular - Angular,Angularfire2,获取数据库中数字的平均值
问题描述
几天来,我一直试图弄清楚这一点。我觉得它比我想象的要简单得多。我正在使用 angular 和 angularfire2 我设置了评级系统,基本上我要做的是查询集合并获取每个文档中的数字字段,将它们加在一起并获得平均值。然而,我所知道的只是查询数据库,并在模板中显示我的所有评论以及如何获取集合中的文档总数,这样我就有了除以的数字。我无法在我的 typscript 文件中弄清楚如何获取所有这些值并将它们加在一起以获取平均值。
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方法得到它。
代码:
this.afs.doc(`productos/${id}`).ref.get().then(function(doc) {
if (doc.exists) {
const reemplazarCantidad = doc.get('cantidadActual') + cant;
console.log('Datos:', doc.data());
console.log('Hay:', doc.get('cantidadActual'));
console.log('Se debe sumar: ', cant);
console.log('total: ', reemplazarCantidad);
} else {
console.log('No hay datos');
}
}).catch(function(error) {
console.log('Error:', error);
});
并且在构造函数中是合乎逻辑的,我将 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。这在我看来是最实用的。
但我不确定它是正确的还是最好的,
谢谢,最好的问候。机器学习
推荐阅读
- javascript - angular应用的目录结构,在角色实现的情况下
- vb.net - 具有多个动态复杂参数的 LINQ GroupBy
- c++ - 查找给定 n 的产品数量的程序的复杂性
- python - 使用索引提取张量的行和列
- r - 如何将一列中的唯一变量以条件提取另一列中的变量并使用输出创建一个新的数据框?
- arrays - 在 TypeScript 中查找比较两个数组的每个匹配项
- php - 从 php 生成的邮件在 Outlook 中没有格式化,但在 Iphone 邮件上看起来很完美
- laravel - Laravel 刀片,这是授权的吗?
- javascript - 将对象推送到数组时,如何不推送相同的对象?
- c++ - What is the purpose of std::add_lvalue_reference and std::add_rvalue_reference?