Angularfire: No easy way to check if an object exists

Created on 28 Jun 2016  路  3Comments  路  Source: angular/angularfire

Currently the most straightforward way to check if an object with a given key exists is to do something like this:

af.database.object('myKey').subscribe((obj) => {
  if (obj.hasOwnProperty('$value') && !obj['$value']) {
    // object does not exist
  } else {
   // object exists.
  }
});

This feels cumbersome for something as common as checking existence, and it's not clear from the docs that this is how you perform this query. I'm not quite sure what the API should be here, but ideally it should be as easy as obj.exists() or perhaps just emitting null if the object doesn't exist?

Firebase(List | Object) feature

Most helpful comment

Much needed functionality. I mean, I guess you could do the following:

this.item = af.database.object('/item', { preserveSnapshot: true });

this.item.subscribe(snapshot => {
if(snapshot.exists()) {  
//object exists 
} else {
 //object doesnt exist 
}
});

Not sure what's the best approach, really.

All 3 comments

Much needed functionality. I mean, I guess you could do the following:

this.item = af.database.object('/item', { preserveSnapshot: true });

this.item.subscribe(snapshot => {
if(snapshot.exists()) {  
//object exists 
} else {
 //object doesnt exist 
}
});

Not sure what's the best approach, really.

I'm running into this with my project now. This would be some nice functionality.

@lf-alves i tried use this solution, but for me do not work.

When a pass {preserveSnapshot:true} . the result is like that !

image

but, the @jteplitz solutions works for me.

  1. How can i solve this problem to use the @lf-alves pattern?

PS: My angularfire2 version is "angularfire2": "^4.0.0-rc.2",

Thank you for attention

Was this page helpful?
0 / 5 - 0 ratings

Related issues

isylhdin picture isylhdin  路  3Comments

fisherds picture fisherds  路  3Comments

martinyoussef picture martinyoussef  路  3Comments

StephenFluin picture StephenFluin  路  3Comments

Maistho picture Maistho  路  3Comments