Search code examples
angularrxjsangularfire2

Display single item from angularfire2 query


Is there any way to display a query from angularfire2 without using a ngFor loop?

this.user = this.af.database.list('items',{
  query: {
    orderByChild: 'id',
    equalTo: id
  }
})

I've tried outputting HTML with all these but only the loop works

{{user}}
{{user | async }}

{{user.name}}
{{user.name | async }}

<h1>{{ (user | async)?.name }}</h1>

<ul>
   <li *ngFor="let u of user  | async" >{{u.name}}</li>
</ul>

dataset is

{
  "items" : {
    "id-1" : {
      "id" : 1,
      "name" : "Gambit"
    },
    "id-2" : {
      "id" : 2,
      "name" : "Wolverine"
    }
  },
  "list" : "bob"
}

also debugging angularfire use to be simple by outputting json to the html, this doesn't seem to work in angularfire2, is there another was of doing this?


Solution

  • You can do it with:

    this.user = this.af.database.list('items',{
      query: {
        orderByChild: 'id',
        equalTo: id
      }
    }).map((items: Array<any>) => items.find(item => item.id === id))
    

    But I would suggest to restructure your data, if you have id you should be able to get item directly:

    this.user = this.af.database.object(`items/${id}`)
    

    Check official docs: Structure Your Database for more details...