0

In my Ionic 2 application using Angular Fire 2, I am trying to get Current User Id in constructor. However, I noticed that the constructor fires twice and though it show capture logged in user's Current ID the second time, the first time it gives an error, like the currentUser object is not defined. Below is the constructor code I am using;

constructor(private afAuth: AngularFireAuth, private afDatabase: AngularFireDatabase, private auth: AuthProvider) {
    console.log('Hello AnonymousTask Provider');

    this.userId = this.afAuth.auth.currentUser.uid;
    console.log(this.userId)

    this.taskList = this.afDatabase.list(`/tasks/${this.afAuth.auth.currentUser.uid}/anTasks`);
}

Below is the console snapshot showing the error message.

enter image description here

I couldn't really understand why the constructor is being fired twice. I understand that on the first time it fired, the Current User object might not be ready.

I tried to use await but the method is synchronous. Any suggestions as to how I could fix this, or what worked for you?

Thr3e
  • 358
  • 1
  • 6
  • 22

2 Answers2

1

I stopped using the synchronous way of fetching the user because sometimes it calls the function before the user is loaded which returns null:

this.afAuth.auth.currentUser.uid;

Instead I now use the asynchronous way and subscribe to it, for example:

this.afAuth.authState.subscribe( user => { 
  this.userId = user.uid;
  this.taskList = this.afDatabase.list(`/tasks/${user.uid}/anTasks`); 
});

That way it makes sure the user is loaded before calling for the userId.

javebratt
  • 351
  • 3
  • 6
0

It's not clear from your code why the constructor is run twice. Looks like the first time your user is still not logged in. What I would do is to check if the entire chain of this.afAuth.auth.currentUser.uid is valid. You can use angularfire's function to test if the user is logged in, or use nested if statements, or use a function like this:

if ( validChain( this, "afAuth", "auth", "currentUser", 'uid' ) ) {
 console.log(this.userId)

 this.taskList = 
 this.afDatabase.list(`/tasks/${this.afAuth.auth.currentUser.uid}/anTasks`);
} else {
  console.log("User seems to be offline!")
}

As a side note, my experience with Angularfire was not fun. Each time Ionic got updated, I had problems with making it work. If you are thinking long term, I recommend using Firebase's own APIs.

Ari
  • 7,251
  • 11
  • 40
  • 70
  • you are right, AF is no fun because of things keeps breaking. Thanks for the suggestions though, i ll try n later update findings here – Thr3e Jul 21 '17 at 22:55