Search code examples
angulartypescriptangularfire2

Angular and AngularFire getting the URL to save as String from Firebase Storage


I'm doing a small my profile update section on a project and I'm following AngularFire's documentation on how to upload files in Firebase, I can successfully upload files thru firebase,however I get a 404 warning in console with the url instead, when I try to console my subscription I get an undefined result. It seems I'm missing an updated syntax or flow which is not currently on the documentation?

Here's my TS

 browseImage($event: any) {
    this.eventImage = $event.files[0];
    this.uploadImage();
  }

  uploadImage() {
    console.log(this.eventImage);

    //Uploads the file into storage
    this.imagePathName = 'profile' + Math.random();
    this.imageRef = this.afsU.ref(this.imagePathName);
    this.imageBaseRef = this.afsU.upload(this.imagePathName, this.eventImage);

    // Gets Image Url for Subscription for real time profile image changing
    this.imageSub = this.imageRef.getDownloadURL();
    this.imageSub.subscribe((url: Observable<string>) => {
      this.imageUrl = url;
    });

    console.log(this.imageSub)
  }

Console Screenshot

enter image description here


Solution

  • In the documentation (https://github.com/angular/angularfire/blob/master/docs/storage/storage.md) I can see that getDownloadURL does not rely on the upload task anymore, which means that it is available before the actual upload is completed. If you want get the download URL after upload is complete, you should stick to the documentation and subscribe to the finalization of the snapshotChanges() observable:

    task.snapshotChanges().pipe(
      finalize(() => this.downloadURL = fileRef.getDownloadURL() )
    )
    .subscribe()
    

    In your case it means following this approach (I suggest to use concatWith in order to subscribe to a new observable once the first one completes):

    this.imageBaseRef.snapshotChanges().pipe(
      concatWith(imageRef.getDownloadURL())
    )
    .subscribe()