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.
your problem is your JSON object students is not an array, and you are trying to loop through it.
you need to make your students a list of objects in order to loop through them, like so:
the loop through
let i of student | async
and access the name and sexi?.name
,i?.sex
AngularFire2 library has gone through some breaking changes since @rickdroio's answer. The following is an updated version of the solution:
I managed to get the key and value of list. Just follow some tips below:
It worked for me, but I am still opening to receive more best practices
With Angular 6
Breakdown:
I created a Map to store the key/values for future queries.
Fetched the values and added them to the previously created Map
todosKeyValues: Map<string, Todo> = new Map();
According to guideline available on https://github.com/angular/angularfire2/blob/master/docs/firestore/collections.md you could do something like that:
It will return a similar array like previous Firebase db.
UPD
with new Angular 6 and RxJS 6 you'll do this: