在 AngularFireAuth 中获取当前用户 [英] Grabbing the current user in AngularFireAuth

查看:26
本文介绍了在 AngularFireAuth 中获取当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取登录用户?

我这样做:console.log('正在登录...');this.afAuth.auth.signInWithEmailAndPassword(this.email, this.password);

I am doing this: console.log('Logging in...'); this.afAuth.auth.signInWithEmailAndPassword(this.email, this.password);

但是文档并不清楚如何在代码中获取用户.它们在模板中显示了一种方式,但我需要存储当前用户.

But the docs are not clear on how to get the user in code. They show a way in the template but I need to store the current user.

推荐答案

获取当前用户:

let user = AngularFireAuth.auth.currentUser;
// returns user object

出于某种原因,每次页面刷新都会导致 currentUser 消失,我将用户 ID (UID) 存储在本地存储中,因此我可以在以后记住用户并引用 Firestore:

For some reason each page refresh causes currentUser to disappear and I store user id (UID) in local storage, so I am able to remember the user and reference to Firestore later:

localStorage.setItem('userUID', user.uid);
// ...
let userID = localStorage.getItem('userUID');
AngularFirestore.firestore.collection('users')
      .doc(userID)
      // ...

在注销时,您只需注销用户并删除本地存储值:

On logout you simply logout user and remove local storage value:

logout() {
   AngularFireAuth.auth.signOut().then(() => {
      localStorage.removeItem('userUID');
   };
}

这篇关于在 AngularFireAuth 中获取当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆