加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularFire2 – 在更新之前检查对象是否存在

发布时间:2020-12-17 17:56:45 所属栏目:安全 来源:网络整理
导读:假设我正在收集用户名,并且我想检查此用户名是否已存在于我的Firebase数据库中. AngularFire2更新或设置方法实际上不会检查对象是否存在,但如果是,则替换它.有没有办法检查并说出返回一个可观察到的错误? 目前我的解决方案是检索对象,如果有结果,我知道它存
假设我正在收集用户名,并且我想检查此用户名是否已存在于我的Firebase数据库中. 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: 'johndoe@example.com',password: '!@#$1234'
     })
   }
});

解决方法

Firebase交易

Firebase为此情况提供了transaction方法.

transaction() is used to modify the existing value to a new value,ensuring there are no conflicts with other clients writing to the same location at the same time.

如果该值不存在,那么您只需返回先前通过更新发送的值.

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

重要的是要注意这是来自Firebase API(不是Angularfire2)的方法,但您仍然可以通过调用$ref来访问这些方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读