Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularFire2: Realtime Database: how to get key and value

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:

<h2>Class size: {{ (class | async)?.numberOfStudent }}</h2>
<ul>
  <li *ngFor="let i of students | async">
    {{i.key}} : {{i.value}}
  </li>
</ul>

What happened:

Class size: 10

Tom :

Mary :

Peter :

Laura :

It doesn't return the value of list.

Any suggestion is appreciated.

like image 762
Phong Vu Avatar asked Oct 05 '17 13:10

Phong Vu


People also ask

How do I get a key in Firebase?

Firebase automatically creates API keys for your project when you do any of the following: Create a Firebase project > Browser key auto-created. Create a Firebase Apple App > iOS key auto-created. Create a Firebase Android App > Android key auto-created.

How do I find my unique key in Firebase?

You can create a unique key in Firebase database using push() and then add child nodes under that key. Now next time when you come to that activity, first check if parent node exists or not. If the node exists, save parent node key and use it to save new child nodes.


2 Answers

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
    });
  }));
like image 198
Ivan Avatar answered Sep 20 '22 07:09

Ivan


I managed to get the key and value of list. Just follow some tips below:

  • Make sure using snapshotChanges()

<li *ngFor="let i of seats | async">
    {{i.key}} : {{i.payload.val()}}
</li>

It worked for me, but I am still opening to receive more best practices

like image 40
Phong Vu Avatar answered Sep 20 '22 07:09

Phong Vu