【问题标题】:Angularfire2 Authentication: How to get the current user?Angularfire2 身份验证:如何获取当前用户?
【发布时间】:2018-08-04 15:42:38
【问题描述】:

在我的 angular-app 中,我使用 angularfire2 身份验证。 打开某个窗口时,我想获取当前用户的邮箱。

为此,我写了如下代码:

ngOnInit() {

    this.currentUserEmail = this.angularFireAuth.authState
      .switchMap(user => {
          console.log("this is a test");
          return user.email;
      });

}

代码遵循此处的文档: https://angularfirebase.com/lessons/google-user-auth-with-firestore-custom-data/#Step-3-Auth-Service

但是,由于某种原因,“switchMap”之后的部分从未输入过”。 所以“这是一个测试”这一行永远不会被打印出来。

如何获取当前用户(和他/她的电子邮件)?

【问题讨论】:

    标签: angular firebase firebase-authentication angularfire2


    【解决方案1】:

    这应该可以正常工作。

    constructor(public afAuth: AngularFireAuth){}
    
    this.afAuth.auth.onAuthStateChanged(user => {
          if (user) {
            // logged in or user exists
          }
          else {
            // not logged in
          }
    })
    

    注意:如上,每次身份验证状态发生变化(登录,注销)时都会触发

    另一种获取用户的方式:

    this.afAuth.authState.subscribe(user => {
       if (user){
    
       }
       else{
    
       }    
    })
    

    您还可以获取其他用户数据。对于电子邮件,您可以调用“user.email”

    【讨论】:

      猜你喜欢
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      • 1970-01-01
      • 2014-11-14
      • 2018-02-05
      • 2018-11-04
      • 1970-01-01
      相关资源
      最近更新 更多