Richard
Richard

Reputation: 8955

How to get the firebase.User in AngularFire2

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.

Upvotes: 2

Views: 2070

Answers (2)

Raphael Jenni
Raphael Jenni

Reputation: 318

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

Upvotes: 2

KhoPhi
KhoPhi

Reputation: 9537

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.

Upvotes: 1

Related Questions