-1

I have a set of images in firebase storage which I'd like to display on the page. I have a function in my service where I want to download all the URLs at once. I'm not sure how I can write it so that photoSrcs only exits after all the subscribe functions have run.

I have pasted the code I have below but obviously, photoSrcs is going to be empty.

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;
  }
Diskdrive
  • 18,107
  • 27
  • 101
  • 167
  • 2
    Possible duplicate of [How to return value from function which has Observable subscription inside?](https://stackoverflow.com/questions/38291783/how-to-return-value-from-function-which-has-observable-subscription-inside) – Reactgular Jan 19 '19 at 13:15

1 Answers1

3

Use forkJoin operator to wait for array of Observables, something like:

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>
Oles Savluk
  • 4,315
  • 1
  • 26
  • 40