Øyvind Hellenes
Øyvind Hellenes

Reputation: 517

How to bypass unique ID and reference child nodes

My firbase database looks like this:

app
   users
       -gn4t9u4ut304u9g4
            email
            uid

How do I reference email and uid? When I try this:

        $rootScope.dashtype.child('users').orderByChild('uid').equalTo($rootScope.auth.uid).on('value', function(snapshot){
            $rootScope.user = snapshot.val();
            console.log($rootScope.user);
        })

I get the correct object, but with the unique id as root:

Object {-JvaZVrWGvJis0AYocBa: Object}

And because this is a dynamic property, I don't know how to reference the child objects. I just want to be able to access the user fields like this: $rootScope.user.email etc.

Upvotes: 1

Views: 4650

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599766

Since you're requesting a value, you get a list of users as a result. It may only be one user, but it's still a list of one.

You will have to loop over the snapshot, to get to the child node:

$rootScope.dashtype.child('users').orderByChild('uid').equalTo($rootScope.auth.uid).on('value', function(snapshot){
    snapshot.forEach(function(userSnapshot) {
        $rootScope.user = userSnapshot.val();
        console.log($rootScope.user);
    });
});

Since there's only a single user in the list, the loop for execute just once.

You are mixing regular Firebase JavaScript with AngularFire here. This means that you will need to inform AngularJS that you updated the scope, so that it will rerender the view:

$rootScope.dashtype.child('users').orderByChild('uid').equalTo($rootScope.auth.uid).on('value', function(snapshot){
    snapshot.forEach(function(userSnapshot) {
        $timeout(function() {
            $rootScope.user = userSnapshot.val();
            console.log($rootScope.user);
        });
    });
});

Upvotes: 3

Related Questions