2016-12-27 124 views
3

假設我正在收集用戶名,並且我想檢查這個用戶名是否已經存在於我的Firebase數據庫中。 AngularFire2 updateset方法實際上並不檢查對象是否存在,但如果存在則替換它。有沒有辦法檢查,並說返回一個可觀察的錯誤?AngularFire2 - 在更新之前檢查對象是否存在

目前我的解決方案是檢索對象,如果有結果,我知道它存在。我正在尋找更直接的方法來檢查。

我需要做的是一個數據庫對象,而不是身份驗證中的實際用戶。

let userExists = false; 

this.af.database.object('/users/' + newUser.name).subscribe(user => { 
    if (user) { 
     userExists = true; 
     console.log('This username is taken. Try another one'); 
    } 
    else { 
     this._af.database.object('/users/' + newUser.name).update({ 
     email: '[email protected]', 
     password: '[email protected]#$1234' 
    }) 
    } 
}); 

回答

5

火力地堡交易

火力地堡提供了這種情況transaction方法。

transaction()用於將現有值修改爲新值,以確保與其他客戶端同時寫入同一位置不存在衝突。

如果該值不存在,那麼您只需返回以前通過update發送的值。

this.af.database.object('/users/' + newUser.name).$ref.transaction(currentValue => { 
    if (currentValue === null) { 
    return {email: '[email protected]', password: '[email protected]#$1234'}; 
    } else { 
    console.log('This username is taken. Try another one'); 
    return Promise.reject(Error('username is taken')) 
    } 
}) 
.then(result => { 
    // Good to go, user does not exist 
    if (result.committed) { 
     // TODO: Take additional action 
    } 
}) 
.catch(error => { 
    // handle error 
}); 

重要的是要注意,這是從火力地堡API(未Angularfire2)的方法是很重要的,但你仍然可以通過調用$ref訪問這些方法。

+0

謝謝! @adriancarriger。有用!!。我在實施中添加了一些額外的細節。 –

+0

太棒了,很高興幫助! – adriancarriger

+0

上述代碼適用於添加新對象。但是嘗試使用它也可以通過'currentValue.remove()'去除,但是獲取錯誤currentValue.remove不是函數。我怎樣才能刪除? – alltej

3

我知道這是一個老問題,但我用這樣AngaularFire4張貼這幫助其他人有類似的問題:

this.db.object(`/users/${uid}`).first().subscribe(x => { 
    if (x.$exists()){ 
      console.log(`FOUND`,x); 
    }else { 
      console.log(`NOT FOUND`); 
    } 
}); 
}