【问题标题】:How do I wait till all subscribes have run before returning function?如何在返回函数之前等到所有订阅都运行?
【发布时间】:2019-06-13 12:21:40
【问题描述】:

我在 Firebase 存储中有一组图像,我想在页面上显示它们。我的服务中有一个功能,我想一次下载所有 URL。我不确定如何编写它,以便 photoSrcs 仅在所有订阅功能运行后才退出。

我已经粘贴了下面的代码,但显然 photoSrcs 将是空的。

loadPhotoUrls(photos : Photo[]) : any
  {
    const photoSrcs = {};

    photos.forEach(async (photo, index) => {
      const fileRef = this.storage.ref('photo.fileLocation');

      fileRef.getDownloadURL().subscribe(url => {
        photoSrcs[photo.id] = url;
      });
    });

    return photoSrcs;
  }

【问题讨论】:

标签: angular rxjs observable firebase-storage


【解决方案1】:

使用forkJoin operator 等待 Observables 数组,类似于:

const { forkJoin, of } = rxjs; // = require("rxjs")

// simulate API call
const fetchFromApi = id => of(`result: ${id}`);

const ids = [1, 2, 3, 4, 5];
const requests = ids.map(fetchFromApi);
forkJoin(requests)
  .subscribe(e => console.log(e))
<script src="https://unpkg.com/rxjs@6.3.3/bundles/rxjs.umd.min.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 2021-08-02
    • 2017-12-21
    相关资源
    最近更新 更多