2017-02-24 52 views
0

我在下面的Firebase中擁有這個json數據結構。我需要創建一個新的子項目,但我想先檢查它是否存在。所以基本上我需要檢查~/parentKey11/childKey21存在之前推新項目(在項目數組中)。如何使用angularfire2檢查Firebase中是否存在父 - 子關聯

"nodeA": [ 
    { 
     "parentKey11": { 
     "childKey21": { 
      "items": [ 
      { 
       ... 
      }, 
      { 
       ... 
      }, 
      { 
       ... 
      } 
      ] 
     }, 
     "childKey22": { 
      "items": [ 
      { 
       ... 
      }, 
      { 
       ... 
      }, 
      { 
       ... 
      }] 
     } 
     } 
    ] 

只是爲了簡單。我可以先檢查父鍵。但是,下面的代碼似乎沒有工作:

const parentRef = this.af.database.object(`/nodeA/parentKey11`, { preserveSnapshot: true }); 

parentRef.subscribe(data => { 
    if(data == null) { 
     console.log('data does not exists') 
    } else { 
     console.log('data exists'); 
     console.log(data); 
    } 
}); 

回答

0

該解決方案適用於我:

const parentRef = this.af.database.object(`/nodeA/parentKey11`, { preserveSnapshot: true }); 

parentRef.subscribe(data => { 
    if(data.val()==null) { 
     console.log('data does not exists') 
    } else { 
     console.log('data exists'); 
    } 
}); 



const parentChildRef = this.af.database.object(`/nodeA/parentKey11/childKey21`, { preserveSnapshot: true }); 

parentChildRef.subscribe(data => { 
    if(data.val()==null) { 
     console.log('data does not exists') 
    } else { 
     console.log('data exists'); 
    } 
}); 
相關問題