我用的是Ionic 2和AngularFire 2和FireBase,这是我的数据结构:
angular - Angularfire 2和Ionic 2-LMLPHP
这是我的代码:carrito.ts

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import {AngularFire, FirebaseListObservable, FirebaseObjectObservable}  from 'angularfire2';
import {ShareService} from '../../pages/services/ShareService';

 @Component({
   selector: 'page-carrito',
   templateUrl: 'carrito.html'
 })



 export class Carrito {
    public restaName:any;
    serviceData: string;
    items: Array<any>;

restas: FirebaseListObservable<any>;
carrito: FirebaseListObservable<any>;
 constructor(public navCtrl: NavController, public navParams: NavParams, af: AngularFire,
  private shareService: ShareService) {
    this.serviceData = shareService.getUserName();
    this.restaName = this.serviceData
    //alert(this.restaName)
    this.restas = af.database.list('/restas', {
      query: {
        orderByChild: 'nombre',
        equalTo: this.restaName
      }
    });


    this.carrito = af.database.list('/carrito', {
      query: {
        orderByChild: 'restaname',
        equalTo: this.restaName
      }

    });


}

这是carrito.html(模板)的一部分
<ion-grid *ngFor="let resta of restas | async">
    <ion-row>
      <ion-col width-25><img style="margin-top: -10px" src="           {{resta.imagen}}" ></ion-col>
      <ion-col width-75>
        <h5>{{resta.nombre}}</h5>
        <span>Comida {{resta.comida}}</span>
        </ion-col>
      </ion-row>
   </ion-grid>

   <ion-list>
    <ion-item  text-wrap *ngFor="let item of carrito | async ">
       <p> {{item.prodname}} </p>
       <p item-right> {{item.cantidad}} </p>
       <p item-right> ${{item.precio}} </p>
       <p item-right (click)="eliminaItem(item.$key)">
       <ion-icon name="trash"></ion-icon>
      </p>
    </ion-item>
   </ion-list>
   ***/////  HERE I WANT TO DISPLAY TOTAL (sum of item.precio) ////***
   <ion-footer *ngIf="total">
    <ion-toolbar>
    <ion-title>Total : $ {{total}} </ion-title>
    </ion-toolbar>
    </ion-footer>
    <ion-toolbar>
    <button full primary clear (click)="sumAriza()">CHECK-OUT</button>
   </ion-toolbar>
   </ion-content>

我一直在阅读Angular Fire 2文档,Ionic 2示例,我有一个愚蠢的问题:如何总结每个对象(行)中的item.precio字段,以获得此列表中的总计(sum)?
提前,谢谢!

最佳答案

好吧,如果你订阅carrito你就会得到你想要的值。
我们来做吧:

//add a total
total: number = 0;
//always save the subscription
totalSubscription: Subscription = null;

ngOnInit() {
   this.totalSubscription = carrito.subscribe((list:any) => {
      this.total = 0; // let's clear the total

      let fixedLength = list.length || 0;
      for (let i = 0; i < fixedLength; i++) {
         this.total += list[i].precio;
      }
   });
}

ngOnDestroy() {
   if (this.totalSubscription !== null) {
       this.totalSubscription.unsubscribe();
   }
}

快乐编码!

08-18 17:19