使变量在 AngularFire5 中可用

Make Variable Available in AngularFire5

我正在尝试从 Firestore 获取一些文档数据,我发现这很容易做到。但是我怎样才能让其他功能可以使用这些数据呢?这是我的代码:

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)

我第一次尝试记录这个名字,它成功了。但是在 }) 之外,我得到 'undefined' 并且我不能在这之外的任何地方使用 this.myFirstName 。我错过了什么?

编辑:在我看来,这个问题似乎在于处理 Firestore 数据的异步性质。所以我想我是在问是否有异步方式来提取这些数据?

因为从 firestore 检索数据本质上是异步的。您应该设置一种方法来异步获取数据,以便您可以在数据可用时获取数据。像这样:

// 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);
  });

如果您真的需要一个工作示例,请告诉我?