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

时间:2018-08-04 15:42:39

标签: angular firebase firebase-authentication angularfire2

在我的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 个答案:

答案 0 :(得分:2)

这应该很好。

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” get email