caraie
caraie

Reputation: 1104

Firebase with AngularFire, ordered and limited join

I'm using AngularFire 2.0.2, and it uses the Firebase SDK 3.x. Since there is no fire-utils for this version, I'm trying to create a normalized collection by hand (specifically an ordered and limited join).

I have a structure like this:

users: {
  user_1: {
    name:...,
    groups: {
      group_1: true,
      group_2: true,
      ...
    }
  },
  ...
},

groups: {
  group_1: {
    group_name: ...,
    last_edited: servertimestamp
  },
  group_2: {
    group_name: ...,
    last_edited: servertimestamp
  }, 
  ...
}

I want to get the first 10 groups of a user ordered by last_edited timestamp.

What's the best approach to do that? Thank you!

Upvotes: 1

Views: 100

Answers (1)

Simon
Simon

Reputation: 797

I'm not sure this is the best way, but when I had to do this recently, this is what I did. (I've unpacked the anonymous functions here, because I find they sometimes confuse things)

Firstly, look up your user:

user = $firebaseObject( firebase.database().ref().child('users').child(username) );

then use the AngularFire $loaded method to check when it's loaded and tell it what to do next:

user .$loaded().then( lookupGroups );

Then create a function called lookupGroups to do the next lookup. This will make an empty array and then loop over all of the groups using angular.forEach

function lookupGroups (){
    $scope.groups= [];
    angular.forEach(user.groups, getGroupData);
}

then write your final getGroupData function which takes the groupid, looks it up and adds the group data to your groups array

function getArkData(key, value){
    grouppath = firebase.database().ref().child('groups').child(value)
    groupData = $firebaseObject( grouppath  );
    $scope.groups.push( groupData );
}

Then you have a $scope.groups array available to use in your front end.

As I say, there might be better ways (I'd be interested to see if anyone has a better way), but this seemed to work for me.

Upvotes: 1

Related Questions