我无法获得编辑或删除的密钥。我拥有循环的所有值但不是密钥。在控制台中我没有任何错误
发票list.component
export class InvoiceListComponent implements OnInit {
invoiceList: IInvoice[];
constructor(private invoiceService: InvoiceService) { }
ngOnInit() {
this.invoiceService.getInvoices().snapshotChanges()
.map(data => data.map(datum => datum.payload.toJSON()))
.map((data : IInvoice[]) => {
return data.map(datum => {
let purchases = [];
for(let key in datum.purchases) {
purchases.push(datum.purchases[key]);
}
datum.purchases = purchases;
return datum;
});
})
.subscribe(data => this.invoiceList = data);
}
onDelete($key: string){
//console.log($key)
this.invoiceService.deleteInvoice($key);
}
}
发票list.html
<table class="table table-sm table-hover table-bordered ">
<thead class="thead-light">
<tr>
<th scope="col">Name</th>
<th scope="col">Total</th>
<th scope="col">Vendor</th>
<th scope="col">Date</th>
<th scope="col">Purchases</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let invoice of invoiceList">
<td>{{invoice.customer.name}} {{invoice.customer.lastname}}</td>
<td>{{invoice.totalPrice}}</td>
<td>{{invoice.uid}}</td>
<td>{{invoice.createdAt}}</td>
<td>
<li class="list-group-item"
*ngFor="let purchase of invoice.purchases">
{{purchase.product.name}}
</li>
</td>
<td>
<a class="btn btn-danger text-white" (click)="onDelete(invoice.$key)">
<i class="fas fa-trash-alt"></i>
</a>
</td>
</tr>
</tbody>
</table>
任何帮助?
这是一个例子(login => user:[email protected] | pass:user123)StackBlitz
问题是$key
的价值未定义。当你做datum.payload.toJSON()
,你失去了$key
相反,你可以使用:
ngOnInit() {
this.invoiceService.getInvoices().snapshotChanges()
.map(data => data.map(datum => {
let purchases = datum.payload.toJSON()['purchases'];
return {
...datum.payload.toJSON() as IInvoice,
$key: datum.key,
purchases: Object.keys(purchases).map(key => purchases[key])
}
}))
.subscribe(data => this.invoiceList = data);
}
通过使用...datum.payload.toJSON()
,我们可以复制该对象的所有值,在下面的行中我们还可以添加$key
。最后,下面的行将purchases
从Object转换为Array。