我有一个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>
并且在typescript文件中我有应该计算总数的构造函数。 几个小时后,我想是时候问:(
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;
});
}
}
答案 0 :(得分: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 :(得分:1)
您尚未初始化var tempnumber;
,因此,它是undefined
,并且当您尝试在循环中对其进行求和时将返回NaN
。
改变这一位:
var tempnumber;
到
var tempnumber = 0;
尝试在块范围变量中使用let
而不是var
。
或使用reduce
let tempnumber = 0;
this.invoiceItem.rows.reduce((total, current) => tempnumber = total + current, tempnumber);
this.totals = tempnumber;