Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用Angular检查Firebase数据库中是否存在数据_Javascript_Angular_Firebase_Firebase Realtime Database - Fatal编程技术网

Javascript 使用Angular检查Firebase数据库中是否存在数据

Javascript 使用Angular检查Firebase数据库中是否存在数据,javascript,angular,firebase,firebase-realtime-database,Javascript,Angular,Firebase,Firebase Realtime Database,我正在使用Angular与Firebase控制台连接的web项目中工作,在保存之前,我使用服务类中定义的此函数验证数据库中是否存在该值,当我在组件中调用此函数时,通常会得到未定义的值 这是我的服务功能: ifExist(category : CategoryType){ firebase.database().ref("/categories/").child("categories").orderByChild("category_

我正在使用Angular与Firebase控制台连接的web项目中工作,在保存之前,我使用服务类中定义的此函数验证数据库中是否存在该值,当我在组件中调用此函数时,通常会得到未定义的值

这是我的服务功能:

  ifExist(category : CategoryType){
    firebase.database().ref("/categories/").child("categories").orderByChild("category_name").equalTo(category.category_name)
.once( "value" , snapshot => {
  if (snapshot.exists()){
    const userData = snapshot.val();
    console.log("exists!", userData);
    return true;
  }
  return false;
});  
}

数据从Firebase异步加载。如果调用(snapshot.exists()){,则
返回false
将在
之前运行,因此您将始终返回false

解决方案是回报承诺:

ifExist(category: CategoryType) {
  return firebase.database().ref("/categories/").child("categories")
    .orderByChild("category_name").equalTo(category.category_name)
    .once("value", snapshot => {
      if (snapshot.exists()) {
        const userData = snapshot.val();
        console.log("exists!", userData);
        return true;
      }
      return false;
    });
}
以及在调用函数时,使用以下选项之一:

ifExist(yourCategoryType).then((result) => {
  console.log("ifExist returned "+result);
});
或者使用更现代的
异步
/
等待

const result = await ifExist(yourCategoryType)
console.log("ifExist returned "+result);
另见:

  • 可能还有更多

请阅读-总结是,这不是向志愿者讲话的理想方式,可能会对获得答案产生反作用。请不要将此添加到您的问题中。那么答案对您有效吗?为什么您当时接受了它?hello@Frank抱歉,但它不起作用我的组件中通常为空