简体   繁体   English

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

[英]Angularfire2 Authentication: How to get the current user?

In my angular-app I am using angularfire2 Authentication. 在我的angular-app中,我正在使用angularfire2身份验证。 When opening a certain window, I want to get the email of the current user. 当打开某个窗口时,我想获取当前用户的电子邮件。

To this end, I wrote the following code: 为此,我编写了以下代码:

ngOnInit() {

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

}

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

However, for some reason, the part after "switchMap" is never entered". So the line "this is a test" gets never printed. 但是,由于某种原因,“ switchMap”之后的部分永远不会输入。因此,“ this is a test”这一行永远不会被打印。

How can I get the current user (and his/her email)? 如何获得当前用户(以及他/她的电子邮件)?

This should work fine. 这应该工作正常。

constructor(public afAuth: AngularFireAuth){}

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

Note: At above, It will trigger every time when auth state have changed (sign-in, sign-out) 注意:在上方,它将在每次身份验证状态更改(登录,注销)时触发

Another way to get user: 获取用户的另一种方法:

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

   }
   else{

   }    
})

You also can get another user data. 您还可以获取另一个用户数据。 For the email you can call 'user.email' 对于电子邮件,您可以调用“ user.email” 取得电子邮件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM