3

So I have code below get the FirebaseObjectObservable. But the path is dynamic as it might not even there yet. So if the path is not there, I want to create that path. But if it is there, I want to update / patch the data.

  this.userLocationDetail = this.af.database.object('/userProfile/' + uid + '/bbwList/' + afLocationId);
  if (this.userLocationDetail) {

    console.log('Data is found');

  } else {
    console.log('Data not found');
  }

The problem is if (this.userLocationDetail) will always be true. How can I look into the observable and make sure it is empty?

Hugh Hou
  • 2,344
  • 5
  • 31
  • 55

1 Answers1

3

You can find out within the observable pipeline. You can .map it if you want to return just an Observable<boolean>. Or you can do something with it within the pipeline.

this.af.database.object('/userProfile/' + uid + '/bbwList/' + afLocationId)
    .subscribe(x => {    
        if (x.hasOwnProperty('$value') && !x['$value']) {
           console.log('data is not found');
        } else {
           console.log('data is found');
        }
    });

If you just want an Observable<boolean>:

this.af.database.object('/userProfile/' + uid + '/bbwList/' + afLocationId)
    .map(x => {    
        if (x.hasOwnProperty('$value') && !x['$value']) {
           return false;
        } else {
           return true;
        }
    });

Or a more condensed version:

this.af.database.object('/userProfile/' + uid + '/bbwList/' + afLocationId)
    .map(x => !x.hasOwnProperty('$value') || x['$value']);
Ryan Langton
  • 6,294
  • 15
  • 53
  • 103