Firebase Reference not returned after add has been called

匆匆过客 提交于 2019-12-11 20:56:47

问题


This is basically a duplicate of this question (I'm sorry for duplicating), but it is on another project, I seem to keep having issues with this, so I am hoping someone can look at the code I have and explain what I keep doing wrong.

Basically I call ADD and I don't get a return value....I am not entirely sure what could be causing it.

function MyController($scope, $firebase, $http, $log) {
        var FB = "https://onaclovtech-home.firebaseio.com/apps/dog/"; // Enter in your FB name
        var ref = new Firebase(FB);
        var emailList = $firebase(ref);
        validateEmail = function (email) { 
           var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
           return re.test(email);
} 
        $scope.addEmail = function(name, email) {
            if (validateEmail(email))
            {
               var newResult = emailList.$add({"name" : name, "email" : email, "validated" : false});
               $log.log(newResult.toString());
               $log.log(newResult.name());

            }

        }

Additionaly Info. This JSFiddle works http://jsfiddle.net/dLFxw/1/ I can't imagine what is going on, but I can only imagine it's related to the controller and how I'm referencing firebase.

I thought maybe it was related to the "limit(1)" I had implemented but that doesn't seem to make a difference.

http://jsfiddle.net/dLFxw/2/


回答1:


The documentation for AngularFire says the following for $add:

This method returns a promise that will be fulfilled when the data has been saved to the server. The promise will be resolved with a Firebase reference, from which you can extract the key name of the newly added data.

It also gives this handy example:

$scope.items.$add({baz: "boo"}).then(function(ref) {
  ref.name();                // Key name of the added data.
});

Ss you can see, they pass in a callback function to the then function.

So if you want to log the name of the new item from the server, you'd do something like:

 emailList
   .$add({"name" : name, "email" : email, "validated" : false})
   .then(function(ref) {
     $log.log(ref.name());
   })

Your confusion seems caused by the asynchronous nature of the $add. When you call $add that results in a call to the server. And although Firebase is normally very fast, there may be cases when this call takes some time to complete. That's why in many of such asynchronous APIs you'll pass in a so-called callback function, in this case to then. You can read it like "Add this to the items, then do that". The Firebase API will then call your function when it completes.



来源:https://stackoverflow.com/questions/24463617/firebase-reference-not-returned-after-add-has-been-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!