0
votes

I am trying to get the user model from firestore. I subscribe to it and can log the user model within the subscription, but when I try and set the outcome to a variable and use it outside of the subscription it returns null.

this.user$ = this.afAuth.authState.pipe(
  switchMap(
    (auth) =>
      (auth)
        ? this.afs.doc(`users/${auth.uid}`).valueChanges()
        : of(null)
  ));

this.user$.subscribe((user) => this.user = user);

console.log(this.user)

So as mentioned, console logging user within the subscription does return the current object, but the outer console.log of this.user returns 'undefined'

EDIT

I am trying to pass the data from this.user into the following get function:

 get userDb() {
    return this.user;
  }

which can then be used throughout the application.

2
This is because the console.log on the last line ran before the data is available.smtaha512

2 Answers

1
votes

Don't forget that this.user$.subscribe ... is asynchronous, therefore, the callback you provided in the subscribe method will be executed AFTER the exection of the console.log statement.

1
votes

So as mentioned, console logging user within the subscription does return the current object, but the outer console.log of this.user returns 'undefined'

there's nothing you can do about it, you have to subscribe to the stream and wait for it to returns, that is the nature of an async operation. All your logic that will depend on this.user will need to stay inside the callback

this.user$.subscribe((user) => {
  this.user = user;
  console.log(this.user);
});