Mar*_*lva 4 firebase firebase-realtime-database angularfire2 angular
假设我正在收集用户名,并且我想检查此用户名是否已存在于我的Firebase数据库中.AngularFire2 update或set方法实际上并不检查对象是否存在,但如果是,则替换它.有没有办法检查并说出返回一个可观察到的错误?
目前我的解决方案是检索对象,如果有结果,我知道它存在.我正在寻找一种更简单的方法来检查它.
我需要将其作为数据库对象,而不是身份验证中的实际用户.
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: 'johndoe@example.com',
password: '!@#$1234'
})
}
});
Run Code Online (Sandbox Code Playgroud)
Firebase 为此情况提供了一种事务处理方法.
transaction()用于将现有值修改为新值,确保与同时写入同一位置的其他客户端不冲突.
如果该值不存在,那么您只需返回之前发送的值update.
this.af.database.object('/users/' + newUser.name).$ref.transaction(currentValue => {
if (currentValue === null) {
return {email: 'johndoe@example.com', password: '!@#$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
});
Run Code Online (Sandbox Code Playgroud)
重要的是要注意,这是来自Firebase API(而不是Angularfire2)的方法,但您仍然可以通过调用来访问这些方法$ref.
| 归档时间: |
|
| 查看次数: |
5117 次 |
| 最近记录: |