抓住AngularFireAuth中的当前用户

时间:2017-10-14 19:50:23

标签: firebase firebase-authentication angularfire2 google-cloud-firestore

如何抓取登录用户?

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

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

4 个答案:

答案 0 :(得分:3)

获取当前用户:

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

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

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

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

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

答案 1 :(得分:0)

我明白了!

console.log('Logging in...');
this.afAuth.auth.signInWithEmailAndPassword(this.email, this.password).then((user) => {
  this.user = this.afAuth.authState;
});

答案 2 :(得分:0)

AngularFireAuth.authState是一个Observable,因此您可以对其进行订阅,然后获取用户实例:

  private user: firebase.User;

  constructor(public afAuth: AngularFireAuth) {
    afAuth.authState.subscribe(user => {
      this.user = user;
    });
  }

答案 3 :(得分:0)

我在网上创建的解决方案,无论页面刷新都有效:

AngularFireAuth.authState.pipe(first()).toPromise();

https://fireship.io/snippets/check-if-current-user-exists-with-angularfire/