0

I'm using firebase in angular/ionic 2 and I need to check if a value exists and to create it if it doesn't however firebase is not returning null as it states in the docs and my check does not run because of it.

subscribeToOffer(uid, offerID) {
    var path = 'users/' + uid + '/offers/' + offerID;

    this.rootRef.child(path).on('value', subscribed => {
        if (subscribed.val() !== null) {
            console.log('subscribed');
        } else {
            console.log('not subscribed');
        }
    });
}
Lindstrom
  • 795
  • 1
  • 5
  • 10
  • If it doesn't return null then what does it return? And are you sure the path is correct? Maybe add a sample of the data you are using in your question (as text, not an image please) – André Kool Mar 21 '16 at 21:44
  • It doesn't return at all, nothing happens. The path is correct because when an offer exists it runs but when theres not it does nothing, I need something back to execute my else statement. – Lindstrom Mar 22 '16 at 09:24
  • Did you try this: https://www.firebase.com/docs/web/api/datasnapshot/exists.html – André Kool Mar 22 '16 at 09:28
  • Or looked at this: http://stackoverflow.com/questions/24824732/test-if-a-data-exist-in-firebase – André Kool Mar 22 '16 at 09:29
  • Hi yeah tried, hasChild() and modified the path with no luck also tried exists() the same thing happens. I have a console.log(subscribed.val()); and it doesn't run when theres no child, it should return null. firebase version 241 – Lindstrom Mar 22 '16 at 11:10

1 Answers1

0

Here i have write a simple function for you that will return true if offer id exist and false in other case.

subscribeToOffer(userId,offerId){
        var userRef = new Firebase(FBURL+'users');
        var userOfferRef = userRef.child(userId).child("offers");
        return userOfferRef.on("value", function(snap) {
          var offerIds = snap.val();
          return !!offerIds.hasOwnProperty(offerId);
        });
  };
Imran Tufail
  • 480
  • 5
  • 12