简体   繁体   中英

Check if data exist in Firebase database with Angular

I'm working on web project with Angular connected with Firebase console and I used this function defined in my service class to verify if the value exists in the database before saving, When I call this function in my component I usually get undefined value .

This is my service function:

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

Data is loaded from Firebase asynchronously. Your return false runs before your if (snapshot.exists()){ is called, so you'll always return false.

The solution is to return a promise:

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

And the use that when calling the function, either with:

ifExist(yourCategoryType).then((result) => {
  console.log("ifExist returned "+result);
});

Or with more modern async / await :

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

Also see:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM