Angular 如何等待async subscribe完全填充全局变量?

Angular 如何等待async subscribe完全填充全局变量?,angular,firebase,asynchronous,angularfire,Angular,Firebase,Asynchronous,Angularfire,我有一个异步firebase调用,类似于: this.fbProvider.fbGetProfile() .subscribe(p => { this.profile = p; }); …但是我需要在其他函数中使用this.profile,例如 console.log(this

我有一个异步firebase调用,类似于:

this.fbProvider.fbGetProfile()
               .subscribe(p => {                                       
                            this.profile = p;
                         });
…但是我需要在其他函数中使用
this.profile
,例如

console.log(this.profile.email);
…并不断返回错误:

无法读取未定义的属性“email”

在我需要使用局部变量之前,你知道如何等待subscribe完全填充我的局部变量吗

ps:我的问题更大,使用
.then()
等解决方案会把我的代码弄得一团糟。我用
wait
尝试了一些东西,但效果不太好


`

您可以使用
async
/
等待
并承诺在api调用完成后解决:

await new Promise(resolve => {
    this.fbProvider.fbGetProfile()
           .subscribe(p => {                                       
                        this.profile = p;
                        resolve();
                     });
});
请记住将
async
放在使用此代码的函数之前

  async uploadToStorage(element) {
    var imgUrl = "";
    var uploadTask = this.gallery_ref.child('Gallery/' + element.name).put(element);
    // Listen for state changes, errors, and completion of the upload.

    await new Promise(resolve => {

      uploadTask.on('state_changed', snapshot => {
        // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
        var progress = (uploadTask.snapshot.bytesTransferred / uploadTask.snapshot.totalBytes) * 100;
        console.log('Upload is ' + progress + '% done');
        }
      }, error => {

      }, function () {
        // Upload completed successfully, now we can get the download URL
        uploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {
          imgUrl = downloadURL;
          console.log("url");
          console.log(imgUrl);
          resolve();
        });
      });
    })
    return imgUrl
  }

这是一个firebase函数,用于跟踪上载到firebase存储的文件的状态更改。使用上面答案中给出的“等待”,对我有效

如果对我的问题投了反对票,请解释为什么我可以改进它,并从中学习。由于对可观察事物如何工作的误解,经常会出现对承诺的回退。你有问题。如果你在其他函数中需要这个结果,那么你需要在这些函数中订阅这个流,而不是在这个地方。@estus,很抱歉,我没有得到它。你是说“订阅”返回“可观察”然后“返回”承诺?这两种方法需要不同的东西?
subscribe
返回一个订阅,而且在上面的代码中完成得太早了
subscribe
应该在使用可观察对象的点上完成(实际上需要
profile
),否则应该使用RxJS操作符合并/修改流。承诺和观察有一些共同点,有时是可互换的,但它们在正确使用时会导致不同的编码习惯。@estus,你有什么内容可以让我对这两种“编码习惯”进行更多的研究吗?已经有toPromise操作符了。车轮正在被重新改造,而且方式不正确。错误将导致未决承诺。