Angular + firebase - 无法获取 html 中的键值

Angular + firebase - can't get the key value in html

我想根据数据库中对象的键导航到 URL,但是当我访问 p.$key 值时始终未定义。

服务:

 getAll(){
    return this.db.list('/products').valueChanges();
  }

组件:

 products$;

  constructor(private productService: ProductService) { 

    this.products$ = this.productService.getAll();
    
  }

html:

<table class="table">
    <thead>
        <tr>
            <th>Title</th>
            <th>Price</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let p of products$ | async">
            <td>{{p.title}}</td>
            <td>{{p.price}}</td>
            <td>
                <a [routerLink]="['/admin/products/', p.$key]" >Edit</a>
            </td>
        </tr>
    </tbody>
</table>

我得到 p.title 和 p.price 的正确值,但 p.$key 始终未定义。我也试过 p.key ,同样的事情。

valueChanges() 流不包含节点的键。根据关于 [valueChanges] 的 AngularFire 文档(您什么时候不使用它?- 当您需要比数组更复杂的数据结构,或者您需要每个快照的键用于数据操作方法时。此方法假定您要么保存快照数据的密钥,要么使用“只读”方法。):

When would you not use it? - When you need a more complex data structure than an array or you need the key of each snapshot for data manipulation methods. This method assumes you either are saving the key for the snapshot data or using a "readonly" approach.

我认为您可能想改用 snapshotChanges stream,它为您提供每个对象的整个 DataSnapshot,您可以从中获得 keyval().

服务:

不需要管道。我使用它是为了让您可以 console.log 查看您的对象。

  getAll(){
    return this.db.list('/products').snapshotChanges()
    .pipe(
      map(object => {
        console.log(object);
        return object;
      })
    );
  }

组件

和你的一样

html

<span *ngFor="let item of items$ | async">
    <!-- print out the key values -->
    {{item.key}}
</span>