【问题标题】:access real time database within onAuthStateChanged在 onAuthStateChanged 中访问实时数据库
【发布时间】:2018-10-09 02:40:34
【问题描述】:

我在使用 Auth 创建用户后尝试访问 firebase 数据库,但没有成功。 使用 Auth 创建用户后,我想将其保存在实时数据库中并添加更多字段。

signUpBrother(email: string, password: string) {
  this.fireAuth.auth.createUserWithEmailAndPassword(email, password)

  this.fireAuth.auth.onAuthStateChanged(function(user) {
    this.firebase.list('brothers').set(uid, {
      'email': user.email,
      'nickname': 'nickname',
      'avatar': 'avatar',
      'is_big_brother': true
    })
  })
}

我得到的错误是:

错误错误:未捕获(承诺中):TypeError:无法读取未定义的属性“firebase”

感谢您的帮助!

【问题讨论】:

  • this onAuthStateChanged 内部的对象与您期望的不同。在 onAuthStateChanged 之前执行var _this = this; 之类的操作,然后在回调中使用变量

标签: javascript angular firebase firebase-realtime-database firebase-authentication


【解决方案1】:

正如 codtex 评论的那样,this 在回调中的含义与在回调之外的含义不同。并且新的this 没有firebase 属性。

为确保您可以访问您的函数,您可以使用不同的名称捕获this

signUpBrother(email: string, password: string) {
  this.fireAuth.auth.createUserWithEmailAndPassword(email, password)

  var that = this;    
  this.fireAuth.auth.onAuthStateChanged(function(user) {
    that.firebase.list('brothers').set(uid, {
      'email': user.email,
      'nickname': 'nickname',
      'avatar': 'avatar',
      'is_big_brother': true
    })
  })
}

【讨论】:

    猜你喜欢
    • 2012-05-12
    • 2021-04-22
    • 2020-08-13
    • 2019-04-13
    • 2021-04-13
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多