I am doing my project in ionic 6 with angular and a firebase database. I need a typescript function that adds the values fetched from an array that are extracted from a collection in firebase.
async getGastos() {
const uid = await this.auth.getUid();
const ruta = 'Usuarios/' + uid + '/Gastos';
this.firebaseService.getCollection<Gasto>(ruta).subscribe(res => {
this.gastos = res;
});
this.setTransc()
}
//Function to fetch the data from the "expenses" collection, the "expense_amount" column and add this data to the "setTransc" function
async getIngresos() {
const uid = await this.auth.getUid();
const ruta = 'Usuarios/' + uid + '/Ingresos';
this.firebaseService.getCollection<Ingreso>(ruta).subscribe(res => {
this.ingresos = res;
this.setTransc()
});
}
//Function to fetch the data from the "income" collection, the "expense_amount" column and add this data to the "setTransc" function
setTransc() {
let sumaGastos = 0;
this.gastos.forEach(gasto => {
sumaGastos += gasto.monto_gasto
console.log("ggg", sumaGastos);
});
let sumaIngresos = 0;
this.ingresos.forEach((ingreso, i) => {
sumaIngresos += ingreso.monto_ingreso
console.log("iii", sumaIngresos);
});
}
async todo(){
await this.getGastos();
await this.getIngresos();
}
"setTransc()" function to sum the values of the array, then the "todo()" function has an await since the elements return a promise before being displayed.
It should be noted that I need to press a button for the values to be operated because I don't know how to do it in the background to show it directly in the view.
What I have tried:
I've used the "setTrasc()" function to call the other get functions you see at the beginning. At the moment the result is that all the quantities of the array are brought and at the last one a number appears that corresponds to the sum of the previous ones.
In this way:
13
90
185
32
320 (amount resulting from the sum of the above)