Firebase .once():使用成功和失败回调

时间:2016-09-13 12:42:40

标签: angularjs firebase firebase-realtime-database

我的Angular-app

中有以下功能
$scope.retrieveProjectData = function() {
        $scope.projectNumberNoChange = false;

        // Only retrieve Data if the ProjectNumber changed
        if (currentlySelectedProjectNumber != $scope.feedback.projectNumber.content) {
            currentlySelectedProjectNumber = $scope.feedback.projectNumber.content;

            // Go to database-reference based on the projectNumber
            var projectsRef = firebaseDatabaseRef.child("projects");
            var currentChild = projectsRef.child(currentlySelectedProjectNumber);

            // retrieve data once and fill $scope.feedback
            currentChild.once("value",
                // If the project is found
                function (dataSnapshot) {
                    // Fill selectedProject and hand over to writeDataFromSelectedProject()
                    var selectedProject = dataSnapshot.val();

                    // Fill $scope.feedback
                    writeDataFromSelectedProject(selectedProject);
                },

                // If no data is found
                function () {
                    console.log("No data found");
                });
        }
        // If the projectNumber didn't change, the projectNumberNoChangeMessage will be shown
        else {
            $scope.projectNumberNoChange = true;
        }
    };

用户可以加载一些有关其项目编号的数据(例如:姓名,电子邮件,电话),以便用户填写表格更快。

在部分中:

currentChild.once("value",
                // If the project is found
                function (dataSnapshot) {
                    // Fill selectedProject and hand over to writeDataFromSelectedProject()
                    var selectedProject = dataSnapshot.val();

                    // Fill $scope.feedback
                    writeDataFromSelectedProject(selectedProject);
                },

                // If no data is found
                function () {
                    console.log("No data found");
                });

只调用第一个Callback函数,即使找不到projectNumber也是如此。如何使用in the docs所描述的“failureCallbackOrContext”?

感谢您抽出宝贵时间!

1 个答案:

答案 0 :(得分:2)

问题解决了。我刚刚检查了dataSnapshot.val()以获取对象或null!