Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase .once(): Use success and failure callbacks

I have the following function in my 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;
        }
    };

The user has the possibility to load some data regarding his project-number (for instance: Name, email, tel) to make it faster for the user to fill a form.

In the part:

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

only the first Callback-function is called, even if the projectNumber was not found. How can I use the "failureCallbackOrContext" as described in the docs?

Thanks for taking the time!

like image 946
Enzo Volkmann Avatar asked Jan 01 '26 15:01

Enzo Volkmann


1 Answers

The problem was solved. I just checked the dataSnapshot.val() for beeing an object or null!

like image 141
Enzo Volkmann Avatar answered Jan 03 '26 13:01

Enzo Volkmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!