0

I'm new in Cloud FireStore and have been searching for many days without results, for a simple solution on how can I sum some fields value of an array coming from Observable Angular Firestore. I have a list of rows and I want sum and have the column total, here is part of my code:

constructor(private afs: AngularFirestore, private router: Router,  private route: ActivatedRoute) { 
    this.negocio = this.route.snapshot.queryParams['negocioId']
    this.movtosCollectionRef = this.afs.collection('movtos', ref => ref.where('empresa', '==', this.negocio));


    this.movtos$ = this.movtosCollectionRef.snapshotChanges().map(actions => {
        return actions.map(action => {
          const data = action.payload.doc.data() as Movtos;
          const id = action.payload.doc.id;
          return { id, ...data };
        });


    });   
  }

In my template I make the browse :

      <tbody>
            <tr *ngFor="let item of movtos$ | async" [class.completed]="item.completed">
                <td>{{ item.indate | date: 'dd/MM/yyyy - HH:mm:ss'}}</td>
                <td>{{ item.concepto }} </td>
                <td>{{ item.tipomov }} </td>
                <td>{{ item.inuser }} </td>
                <td>{{ item.importe |  currency:'USD':true:'3.2-2' }}</td>
                <td>
                    <a class="btn btn-info" (click)="editaEmpresa(item.id)" tooltip="Edita Movimiento" placement="top"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span></a>

                </td>

            </tr>   

        </tbody>

And I want to get the sum of item.importe field. Does any body know how to do this? Best regards, Caribesoft

1 Answer 1

1

You can use map on the Observable to return the sum. eg

getSum(): Observable<number> {
    return this.observable
       .map(arr => arr.reduce((a, b) => a + b.value, 0));
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Rahul for your response, but where do I get "this.observable" ? I tried with this.movtos$ but it does not work.
Are you getting the response as a promise? Then you can use Observed.fromPromise()
I'm trying this -> getSum(): Observable<number> { return this.movtos$ .map(arr => arr.reduce((a, b) => a + b.importe, 0)); } but I get TOTAL: [object Object]
Can you try and log what the object holds?
Hi, thank you, I resolved using Subscription this way : this.totalSubscription = this.movtos$.subscribe((list:any) => { this.total = 0; let fixedLength = list.length || 0; for (let i = 0; i < fixedLength; i++) { this.total += list[i].importe; } }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.