2017-02-05 97 views
1

我有一個ngFor和發票總額是計算價格和時間 的,但我還是希望所有總如何總結所有表中字段

<tr *ngFor="let invoice of invoiceItem.rows"> 
    <td>{{ invoice.rowName }}</td> 
    <td>{{ invoice.hours}}</td> 
    <td>{{ invoice.price }}</td> 
    <td>{{ invoice.comments }}</td> 
    <td>{{ invoice.total}} </td> 

</tr> 
<tr> 
    <td></td> 
    <td></td> 
    <td></td> 
    <td>total ex 18%</td> 
    <td>{{ totals }}</td> 
</tr> 

,並在打字稿文件總計我有構造函數應該計算總數。 多小時後,我認爲它的時間來問:(

export class DemoTestComponent { 
    public invoiceItem: ItemInvoice; 
    public invoiceItem2: ItemInvoice; 

    public invoices: InvoiceData; 
    public invoiceRows: InvoiceDetailsRows[]; 
    public totals: number; 
    //public theTex: number; 
    //public totalsAfterTax: number; 
    constructor(http: Http) { 
     http.get('/api/Invoice/test/1').subscribe(result => { 
      this.invoiceItem = result.json(); 
      this.invoiceItem.rows.forEach((item) => { 
       item.total = calculate(item); 
      }) 
      var tempnumber; 
      this.invoiceItem.rows.forEach((item) => { 
       tempnumber += item.total; 
      }) 
      this.totals = tempnumber; 
      //this.theTex = this.totals * 0.18; 
      //this.totalsAfterTax = this.totals + this.theTex; 

     }); 

    } 
} 

回答

1

可能是你所面臨的問題是,因爲你是在構造函數中調用這個的。你應該把它在ngoninit。我們所有的http請求應在生命週期掛鉤不是在構造函數中。

export class DemoTestComponent { 
      public invoiceItem: ItemInvoice; 
      public invoiceItem2: ItemInvoice; 

      public invoices: InvoiceData; 
      public invoiceRows: InvoiceDetailsRows[]; 
      public totals: number; 
      //public theTex: number; 
      //public totalsAfterTax: number; 
      constructor(http: Http) { } 
      ngOnInit() { 
       http.get('/api/Invoice/test/1') 
        .map(result => result.json()) 
        .subscribe(result => { 
        this.invoiceItem = result; 
        this.invoiceItem.rows.forEach((item) => { 
         item.total = calculate(item); 
        }) 
        var tempnumber=0; 
        this.invoiceItem.rows.forEach((item) => { 
         tempnumber += item.total; 
        }) 
        this.totals = tempnumber; 
        //this.theTex = this.totals * 0.18; 
        //this.totalsAfterTax = this.totals + this.theTex; 
       }); 
      } 
      } 

你得到任何錯誤?如果你仍然得到那麼任何錯誤顯示您的JSON數據。我將編輯我的答案。

1

您還沒有初始化var tempnumber;,因此,是undefined,當您嘗試在循環中對其進行求和時,將返回NaN

更改該位:

var tempnumber; 

var tempnumber = 0; 

,並嘗試使用塊let範圍的變量,而不是var

或用減少

let tempnumber = 0; 
this.invoiceItem.rows.reduce((total, current) => tempnumber = total + current, tempnumber); 

this.totals = tempnumber; 
相關問題