首页 > 解决方案 > 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);
  });

标签: angularfirebasegoogle-cloud-firestoreangularfire2

解决方案


我遇到了类似的问题,但是我能够获取数据并将数字放入变量中,问题是我无法在内部执行 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。这在我看来是最实用的。

但我不确定它是正确的还是最好的,

谢谢,最好的问候。机器学习


推荐阅读