Search code examples
firebasefirebase-storageangularfire2

AngularFire2 - Firebase storage getDownloadURL() - How to return the url for firestore


I've been going through the angularfire2 documentation to retrieve a downloadURl from storage. I'm hoping I'm missing something simple here.

The documentation states:

@Component({
  selector: 'app-root',
  template: `<img [src]="profileUrl | async" />`
})
 export class AppComponent {
   profileUrl: Observable<string | null>;
   constructor(private storage: AngularFireStorage) {
   const ref = this.storage.ref('users/davideast.jpg');
   this.profileUrl = ref.getDownloadURL();
 }
}

However, once I've uploaded an image I want to return the download url as a string to upload to firestore. I need the download URL for an external service.

My function

uploadImage(base64data) {

  const filePath = (`myURL/photo.jpg`);
  const storageRef = firebase.storage().ref();

  var metadata = {
    contentType: 'image',
    cacheControl: "public, max-age=31536000",
  };

  const ref = this.storage.ref(filePath);
  const task = ref.putString(base64data, 'data_url', metadata).then(() => {

    var downloadURL = ref.getDownloadURL();

  })

}

This uploads the image perfectly fine. However, I would then like to write the download URL to firestore. When console logging my 'downloadURL' variable, I get the following:

PromiseObservable {_isScalar: false, promise: y, scheduler: undefined}

The download is inside the promise observable. How do I just get the download URL string as my variable? Once I have that I can sort the firestore updates out.


Solution

  • This answer is not relevant from Firebase 5.0 release, they removed downloadURL() from upload task. Please refer to doc.

    The .downloadURL() observable emits the download URL string once the upload is completed. Then you need to subscribe to get the value.

    uploadImage(base64data) {
    
      const filePath = (`myURL/photo.jpg`);
      //const storageRef = firebase.storage().ref();
    
      var metadata = {
        contentType: 'image',
        cacheControl: "public, max-age=31536000",
      };
    
      const ref = this.storage.ref(filePath);
      const task = ref.putString(base64data, 'data_url', metadata);
      const downloadURL = task.downloadURL();
    
      downloadURL.subscribe(url=>{
         if(url){
             console.log(url);
             //wirte the url to firestore
         }
      })
    
    }
    

    Hope this helps. check this blog for more detail