1
votes

I can't seem to be able to get a download url for an image in storage based on filename.

Correction, I can, but i can't seem to get the variable out of the function. Eg. My code:

 public getVenueImage(image: string){
    let imgUrl: string;
    try{
      this.firebase.storage().ref().child("/venues/" + image ).getDownloadURL().then(function(url){
        imgUrl = url;
        console.log("log1: " + url);
      });
    }
    catch(e){
      console.log(e);
    }
    console.log("log2: " + imgUrl);
    return imgUrl;
  }

Log1: https://firebasestorage.googleapis.com/v0/b/icorp-dashboard.appspot.com/o/venues%2Fcinema.jpg?alt=media&token=e5be11ef-f53f-48dc-ab79-a81a50c0e317

Log2: undefined

Any reason why I can't get the image link to return?

1

1 Answers

2
votes

because using promise with then makes your task asynchronous and it's placed in the event queue to be executed later, so the console.log("log2: " + imgUrl); is executed before the imgUrl = url;

 public getVenueImage(image: string){
    let imgUrl: string;
    try{
      this.firebase.storage().ref().child("/venues/" + image ).getDownloadURL().then(function(url){
        console.log("log1: " + url);
        return url;
      });
    }
    catch(e){
      console.log(e);
    }   
}