Firebase 3 get list which contain generated keys t

2019-07-30 01:44发布

问题:

I wanna synchronize firebase table with ionic list.

These are items on database

Items
 -KQpA9YpXyqBQ2HZedEo
       name:     "jhj"
 -KQpAWtIaMeS93431BRQ
       name:     "hj"
 -KQpB6grRt15GnacKHjW
       name:     "j"

This is ionic part

 <ion-list>
     <ion-item ng-repeat="item in items">
          <h2>{{item.name}}</h2>
     </ion-item>
 </ion-list>

Here is my firebase part

var itemsRef = firebase.database().ref('Items');

//first try
var items = itemsRef.orderByChild('name');
$scope.items = items;

//this is second try
itemsRef.on('child_added', function (data) {
    $scope.items = data.val();
});

If I try something like this I can see Items on console.

 var items = itemsRef.orderByChild('name');

 items.on('child_added', function (snapshot) {
     var obj = snapshot.val();
     console.log(obj);
 });

I need help to get and show the list on ionic.

回答1:

Using $firebaseArray is the solution

var itemsRef = firebase.database().ref('Items');
var itemsQuery = itemsRef.orderByChild('name');
$scope.items = $firebaseArray(itemsQuery);

Angular Fire Docs



回答2:

I think using $firebaseObject is better.

Check this out

var itemsRef = firebase.database().ref('Items');
var items = itemsRef.orderByChild('name');
$scope.items = $firebaseObject(items); // Don't forget to add $firebaseObject in your dependencies of your controller

Now in your view you can do the following

<ion-list>
     <ion-item ng-repeat="(key, item) in items">
          <h2>{{item.name}}</h2>
     </ion-item>
 </ion-list>

You will be also to use the key by writing {{key}}, useful if you need to navigate to it's details page. And by using this, you get all the child events (added, changed and removed)