如何从 Firebase 中的 snapshot.val() 或 snapshot.exportVal() 获取属性/值?

Bei*_*man 1 javascript firebase angularfire firebase-realtime-database

snapshot如此CodePen所示,我能够获取我感兴趣的对象

以下是代码片段:

$scope.post = {};
        var postsRef = new Firebase('https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts');

        $scope.searchPost = function () {
            console.log('searched for author : ' + $scope.post.authorName);

            postsRef.orderByChild('author')
                .equalTo($scope.post.authorName)
                .once('value', function (snapshot) {
                    var val = snapshot.val();
                    console.log("Searched Post is : ");
                    console.log(val);
                    console.log("(From Val) Title is : " + val.title);

                    var exportVal = snapshot.exportVal();
                    console.log("Export Value is : ");
                    console.log(exportVal);
                    console.log("(From Export Val) Title is : " + exportVal.title);
                });
        }
Run Code Online (Sandbox Code Playgroud)

这是我使用的Firebase 数据集

当我搜索 author: 时gracehop,我得到了正确的快照,但是,我无法访问title里面的属性。无论val.titleexportVal.title被给予undefined作为输出。

如何从快照中获取感兴趣的属性?

car*_*ant 5

该查询返回一个包含匹配子项的快照,而这些子项包含您感兴趣的属性。

您可以使用快照的forEach方法枚举子项:

postsRef.orderByChild('author')
    .equalTo($scope.post.authorName)
    .once('value', function (snapshot) {

        snapshot.forEach(function (childSnapshot) {

            var value = childSnapshot.val();
            console.log("Title is : " + value.title);
        });
    });
Run Code Online (Sandbox Code Playgroud)