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

CaribeSoft
  • 577
  • 1
  • 8
  • 25

1 Answers1

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));
}
Rahul Singh
  • 19,030
  • 11
  • 64
  • 86
  • Thanks Rahul for your response, but where do I get "this.observable" ? I tried with this.movtos$ but it does not work. – CaribeSoft Dec 24 '17 at 18:51
  • Are you getting the response as a promise? Then you can use `Observed.fromPromise()` – Rahul Singh Dec 24 '17 at 18:51
  • I'm trying this -> getSum(): Observable { return this.movtos$ .map(arr => arr.reduce((a, b) => a + b.importe, 0)); } but I get TOTAL: [object Object] – CaribeSoft Dec 24 '17 at 19:17
  • Can you try and log what the object holds? – Rahul Singh Dec 25 '17 at 03:52
  • 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; } } – CaribeSoft Dec 25 '17 at 22:16