How to get currently logged in auth state/user from angularfire2

前端 未结 4 1431
囚心锁ツ
囚心锁ツ 2021-02-05 18:55

I have an ionic2 app and am using Firebase and angularFire2. I\'d like to get the current authentication state and current auth object/user from firebase using angularFire2.

相关标签:
4条回答
  • 2021-02-05 19:16
    1. Import: import { AngularFireAuth } from 'angularfire2/auth';
    2. Inject: constructor(public afAuth: AngularFireAuth) { }
    3. Check:

      this.afAuth.authState.subscribe(res => {
        if (res && res.uid) {
          console.log('user is logged in');
        } else {
          console.log('user not logged in');
        }
      });
      
    0 讨论(0)
  • 2021-02-05 19:20

    You can simply import AngularFireAuth and do this:

    this.angularFireAuth.authState.subscribe(userResponse => {
      if (userResponse) {
        console.log('here is your user data');
        localStorage.setItem('user', JSON.stringify(userResponse));
        console.log(userResponse);
      } else {
        localStorage.setItem('user', null);
      }
    });
    

    Here i am also using localStorage to save all data of my current user active on my app.

    0 讨论(0)
  • 2021-02-05 19:25

    now in order to get the user info, you have to subscribe for getting the auth information. Ex

      constructor(public af: AngularFire) {
        this.af.auth.subscribe(auth => console.log(auth));// user info is inside auth object
      }
    

    auth object will be null if auth state does not exist

    0 讨论(0)
  • 2021-02-05 19:39

    current authentication state is available from the injected FirebaseAuth. You can get the actual auth data auth.getAuth()

    See: https://github.com/angular/angularfire2/blob/master/src/providers/auth.ts#L99

    0 讨论(0)
提交回复
热议问题