Nicu Raul
Nicu Raul

Reputation: 13

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

I want to navigate to an URL based on the key of an object in my database, but when i acces the p.$key value is always undefined.

service:

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

component:

 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>

enter image description here I am getting the right values for p.title and p.price, but p.$key is always undefined. I also tried p.key , same thing.

Upvotes: 1

Views: 1016

Answers (2)

Reza Taba
Reza Taba

Reputation: 1904

Service:

Pipe is not necessary. I used it so you can console.log your object to view.

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

Component

Same as yours

html

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

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 598837

The valueChanges() stream doesn't include the key of the nodes. According to the AngularFire documentation on [valueChanges](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.):

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.

I think you may want to use the snapshotChanges stream instead, which gives you the entire DataSnapshot for each object from which you can get the key and the val().

Upvotes: 2

Related Questions