AngularFire2: Realtime Database: how to get key and value

Phong Vu picture Phong Vu · Oct 5, 2017 · Viewed 19k times · Source

I use AngularFire2 to get data from Firebase Database (realtime).

What I have done:

  • Firebase Database

{ “class” : { “student” : { “Tom” : “male”, “Mary” : “female”, “Peter” : “male”, “Laura” : “female” }, "numberOfStudent” : 10 } }

  • app.component.ts

    import { AngularFireDatabase } from 'angularfire2/database';
    import { Observable } from 'rxjs/Observable';
    
    ...
    export class AppComponent {
    
       class: Observable<any>;
       students: Observable<any[]>;
    
    constructor(private db: AngularFireDatabase) {
       this.class = db.object(‘class’).valueChanges();
       this.students = db.list(‘class/student’).snapshotChanges();
     }
    
    } 
    
  • app.component.html:

What happened:

Class size: 10

Tom :

Mary :

Peter :

Laura :

It doesn't return the value of list.

Any suggestion is appreciated.

Answer

Ivan picture Ivan · Jun 7, 2018

UPD

with new Angular 6 and RxJS 6 you'll do this:

import { map } from 'rxjs/operators';
// ...
return this.fb.list(`/path/to/list`)
  .snapshotChanges()
  .pipe(map(items => { .            // <== new way of chaining
    return items.map(a => {
      const data = a.payload.val();
      const key = a.payload.key;
      return {key, data};           // or {key, ...data} in case data is Obj
    });
  }));