循环中缺少键(角度5)

时间:2018-09-07 22:50:41

标签: angular angular5 angularfire2

我无法获取编辑或删除的密钥。我拥有循环的所有值,但没有钥匙。在控制台中,我没有任何错误

invoice-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);
 }
}

invoice-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>

有什么帮助吗?

这里是示例(登录=> user:user@user.com | pass:user123)StackBlitz

1 个答案:

答案 0 :(得分:1)

问题在于$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从一个对象转换为一个数组。

Here is a StackBlitz demo