2016-09-28 45 views
3

所以我有下面的代碼獲取FirebaseObjectObservable。但路徑是動態的,因爲它可能還沒有。所以如果路徑不在那裏,我想創建這條路徑。但如果它在那裏,我想更新/修補數據。我如何知道FirebaseObjectObservable爲空?

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

    console.log('Data is found'); 

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

問題是如果(this.userLocationDetail)將始終爲真。我怎樣才能看到可觀察的並確定它是空的?

回答

3

你可以在可觀察的管道內找到。如果你想返回一個Observable<boolean>,你可以.map。或者你可以在管道內用它做點什麼。

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

如果你只是想一個Observable<boolean>

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

還是更濃縮版本:

this.af.database.object('/userProfile/' + uid + '/bbwList/' + afLocationId) 
    .map(x => !x.hasOwnProperty('$value') || x['$value']); 
+0

謝謝!任何示例以及可觀察的方法? –

+0

我添加了一個可觀察的代碼