0

I am trying to get some Document data from Firestore, which I have found easy enough to do. But how can I then make that data available to other functions? Here's my code:

let documentRef = this.afs.collection('profiles').doc(this.userId);

var myProfileRef = documentRef.ref.get()
.then(doc => {
    this.myFirstName = doc.data().firstName;
    console.log(this.myFirstName)
})

console.log(this.myFirstName)

The first time I try to log the name, it works. But outside of the }) I get 'undefined' and I cannot use this.myFirstName anywhere outside of this. What am I missing?

EDIT: It seems to me as though this problem lies in the asynchronous nature of working with Firestore data. So I guess I'm asking if there's an asynchronous way to pull this data?

Tomislav Stankovic
  • 3,080
  • 17
  • 35
  • 42
Nick
  • 25
  • 5

1 Answers1

1

As retrieving data from firestore is asynchronous in nature. You should setup a way to get your data asynchronously so that you can have your data whenever it is available. Something like this:

// Way 1: function returns observable 
  getName(): Observable<string> {

    return new Observable (observer =>{
      let documentRef = this.afs.collection('profiles').doc(this.userId);
      documentRef.ref.get()
      .then(doc => {
          let myFirstName = doc.data().firstName;
          observer.next(myFirstName);
          observer.complete();
      })
      .catch(error =>{ console.log(error); })
    });
  }

  // Call function and subcribe to data
  this.getName().subscribe(res =>{
    console.log(res);
  });

  // Way 2: Function returns promise
  getFirstName(): Promise<string> {
    return new Promise(resolve =>{
      let documentRef = this.afs.collection('profiles').doc(this.userId);
      documentRef.ref.get()
      .then(doc => {
          let myFirstName = doc.data().firstName;
          resolve(myFirstName);
      })
      .catch(error =>{ console.log(error); })
    })
  }

  // Use it
  this.getFirstName().then(res =>{
    console.log(res);
  });

Let me know if you really need a working example?

sugarme
  • 751
  • 5
  • 9