如何绕过唯一 ID 并引用子节点 [英] How to bypass unique ID and reference child nodes

查看:18
本文介绍了如何绕过唯一 ID 并引用子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 firbase 数据库如下所示:

My firbase database looks like this:

app
   users
       -gn4t9u4ut304u9g4
            email
            uid

我如何引用电子邮件和 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);
        })

我得到了正确的对象,但唯一的 id 是 root:

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

Object {-JvaZVrWGvJis0AYocBa: Object}

而且因为这是一个动态属性,我不知道如何引用子对象.我只想能够像这样访问用户字段:$rootScope.user.email 等

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.

推荐答案

由于您请求的是一个值,因此您会得到一个用户列表.它可能只有一个用户,但它仍然是一个列表.

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.

您在此处将常规 Firebase JavaScript 与 AngularFire 混合使用.这意味着您需要通知 AngularJS 您更新了范围,以便它重新渲染视图:

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);
        });
    });
});

这篇关于如何绕过唯一 ID 并引用子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆