【问题标题】:function doesn't work within the firebase Auth with Angular功能在使用 Angular 的 firebase Auth 中不起作用
【发布时间】:2019-02-21 12:11:17
【问题描述】:

我正在尝试将 Firebase Auth 与我的 Angular7 应用程序一起使用。 我想使用一些功能来处理用户数据。 但是,在我使用谷歌帐户登录后,代码直到 myFunction 工作, 但在 myFunction 不起作用之后 我不确定根本原因,因为没有显示任何消息。

你能给我建议吗?

constructor(private afAuth: AngularFireAuth) {}

public myFunction(obj: any){
  console.log(obj)
}

public socialLogin() {
  var provider = new firebase.auth.GoogleAuthProvider();
  this.afAuth.auth.useDeviceLanguage();
  this.afAuth.auth.signInWithPopup(provider).then(function(result) {
    console.log('logged in'); <- work!
    var user = result.user; <- work!
    console.log(user) <- work!
    this.myFunction(user); <- not work
    console.log('test'); <- not work
  })

打字稿版本是 2.9.2

【问题讨论】:

  • 难道this 没有从回调中引用类吗?尝试在socialLogin() 的顶部添加const self = this;,然后运行self.myFunction(user);。不确定它是否会起作用,但值得一试。

标签: javascript typescript firebase firebase-authentication angular7


【解决方案1】:

使用箭头函数(继承封闭上下文),在您的代码中回调绑定到不同的this

this.afAuth.auth.signInWithPopup(provider).then(result => {
    console.log('logged in'); <- work!
    var user = result.user; <- work!
    console.log(user) <- work!
    this.myFunction(user); <- not work
    console.log('test'); <- not work
  })

【讨论】:

    猜你喜欢
    • 2020-06-04
    • 2014-12-17
    • 1970-01-01
    • 2020-11-05
    • 2018-07-29
    • 1970-01-01
    • 2021-01-26
    • 2021-08-15
    • 2021-10-09
    相关资源
    最近更新 更多