首页 文章

Angularfire2身份验证:如何获取当前用户?

提问于
浏览
1

在我的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”之后的部分永远不会输入“ . 所以”这是一个测试“从未打印过 .

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

1 回答

  • 1

    这应该工作正常 .

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

    注意:在上面,每当auth状态发生变化时都会触发(登录,注销)

    获得用户的另一种方式:

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

    您还可以获取其他用户数据 . 对于电子邮件,您可以致电'user.email'
    get email

相关问题