DEV Community

hsminchala
hsminchala

Posted on

Question - Add values from an array brought from firebase and display them in a label

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.gastos.forEach(gasto => {
            //     gasto.monto_gasto;
            // });
        });
        this.setTransc()
           }
Enter fullscreen mode Exit fullscreen mode

//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.ingresos.forEach(ingreso => {
            //     ingreso.monto_ingreso
            // });
        this.setTransc()
        });
    }
Enter fullscreen mode Exit fullscreen mode

//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();
    }
Enter fullscreen mode Exit fullscreen mode

"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 next view.

Image description
Thanks in advance and sorry for my bad English.

Oldest comments (0)