How to get the firebase.User in AngularFire2

笑着哭i 提交于 2019-12-11 02:55:31

问题


I am using AngularFire2 (Ionic2) and Firebase Authentication.

I am having a problem trying to get the current user. The works for me, but inconsistently. Sometimes it is populated, and sometimes it is null.

let user: firebase.User = firebase.auth().currentUser;

Is there a way to get the current user more consistently?

More Info:

I am logging in as follows:

import { FirebaseAuth, AuthProviders, AuthMethods } from 'angularfire2';

public auth: FirebaseAuth

    this.auth.login({
      provider: AuthProviders.Google,
      method: AuthMethods.Popup
    }).then((data: any) => {
            this.fireAuth.onAuthStateChanged((user) => {
                        ....
            });
    });

Here the user is always populated. But where I need to get access to the user, is in another part of the code.

Any help appreciated.

UPDATE

I try use the following to get the current user:

    this.auth.subscribe((authData) => {
      let user = authData.auth;
        credential = firebase.auth.GoogleAuthProvider.credential(googleIdToken, googleAccessToken);
        user.reauthenticate(credential).then(() => {...
    });

But then when I try create the credentials, I get the following error:

EXCEPTION: Uncaught (in promise): Error: reauthenticate failed: First argument "credential" must be a valid credential.

When I get the current user in the first method, I don't get any errors and it works.

More info:

When I console.log the following user objects, they both look identical:

  let user: firebase.User = this.fireAuth.currentUser;
  console.log(user);

and

    this.auth.subscribe((authData) => {
            let user: firebase.User = authData.auth;
            console.log(user);
    });

but the one works (when not null) and the other cannot reauthenticate.


回答1:


Attention there is a new AngularFire Version. (4.0.0)

In the new version all the modules are split up. That means, you need to use the AngularFireAuth


    constructor(afAuth: AngularFireAuth) {
        afAuth.authState.subscribe(auth => {
          if(auth) {
            console.log('logged in');
          } else {
            console.log('not logged in');
          }
        });
    }

Hope I can help




回答2:


I find this simple approach to work:

constructor(af: AngularFire) {
  af.auth.subscribe(auth => {
    if(auth) {
      console.log('logged in');
    } else {
      console.log('not logged in');
    }
  });
}

More on AngularFire2 Authentication on Github*

  • Disclaimer: Project mine.


来源:https://stackoverflow.com/questions/41899746/how-to-get-the-firebase-user-in-angularfire2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!