Firebase数组始终返回false

时间:2017-02-21 12:57:23

标签: javascript firebase ionic-framework firebase-realtime-database

我正在使用ionic和firebase创建一个应用程序。我试图验证我的数组中是否存在元素,如果存在,我需要返回true,否则我需要返回false。问题是,它总是返回false,即使该项存在于firebase中。你能告诉我下面代码出了什么问题吗?

这是我的服务:

function IsReserved(id){
    var ref = fb.child('/reserved/').orderByChild('product').equalTo(id);
    ref.once("value").then(function(snapshot){
        snapshot.forEach(function(data){
            if(data.val().user === $rootScope.currentUser.$id){
                console.log(data.val().user + " * " + $rootScope.currentUser.$id);
                return true;
            }
        });
    });

    return false;
}

这是我的控制器:

function Reservar(produto) {
if(!$rootScope.cart){
  $rootScope.cart = [];
  $rootScope.fprice = 0;
}

var user=$rootScope.currentUser;
var res = vm.IsReserved(produto.$id);
console.log(res);


if(res){
    console.log("já reservado");                
    return;
}

这是我的firebase结构:

-reserved:
     --KdS2cH1OJ5MhKAV6Yio:
            -product: "product1"
            -user: "W30BB1RMg1XhNo9og9cMo4Gpr4S2"

1 个答案:

答案 0 :(得分:2)

您的代码无效,因为firebase异步工作。

您应该使用回调函数作为参数,如下所示:

function IsReserved(id, callback){
            var ref = fb.child('/reserved/').orderByChild('product').equalTo(id);
            ref.once("value").then(function(snapshot){
                snapshot.forEach(function(data){
                    if(data.val().user === $rootScope.currentUser.$id){
                        console.log(data.val().user + " * " + $rootScope.currentUser.$id);
                        callback(true);
                        return;
                    }
                });
            });
            
            return false; //-- This will always be executed before the code inside the .then, that's why your function always returns false
        }

在你的控制器上,有这样的事情:

function Reservar(produto)
        {
            if(!$rootScope.cart){
              $rootScope.cart = [];
              $rootScope.fprice = 0;
            }

            var user=$rootScope.currentUser;
            vm.IsReserved(produto.$id, function(response){
               console.log(response);
               if(response){
                console.log("já reservado");                
               }
            });
  }
            

你知道吗?

相关问题