0

I'm using Angular and Firebase storage to upload images and I'm having the problem where my urlImg it's undefined when I try to print it in the console.log inside of the tap.

 this.snapshot = this.snapshot = this.task.snapshotChanges().pipe(
      finalize(() => {
        this.storage
          .ref(path)
          .getDownloadURL()
          .subscribe(url => {
            this.urlImg = url; // with this you can use it in the html
          });
      }),
      tap(snap => {
        if (snap.bytesTransferred === snap.totalBytes) {
          // Update firestore on completion
          //Code to upload on completion
          console.log("url");
          console.log(this.urlImg);
        }
      })
    );
Patricio Vargas
  • 5,236
  • 11
  • 49
  • 100
  • That `tap` will occur before the `finalize`, as `finalize` is the last thing that happens – user184994 Oct 21 '18 at 17:34
  • @user184994 ohh i didn't that ! any suggestions? on how to fix this issue? – Patricio Vargas Oct 21 '18 at 17:35
  • It depends what it is you're trying to do really. You can obviously access `this.urlImg` from within that `subscribe` if you need to? – user184994 Oct 21 '18 at 17:36
  • I want to wait for the file to be uploaded, then get the url of the image in Firebase storage then upload to firestore the url from the image located in Firebase Storage @user184994 – Patricio Vargas Oct 21 '18 at 17:38
  • [typescript - wait for an observable/promise to finish, and return observable](https://stackoverflow.com/questions/37304160/typescript-wait-for-an-observable-promise-to-finish-and-return-observable) – HDJEMAI Oct 21 '18 at 18:09
  • [Wait for subscription to complete](https://stackoverflow.com/questions/44162905/wait-for-subscription-to-complete) – HDJEMAI Oct 21 '18 at 18:11

1 Answers1

0

One alternative is to take advantage of the completed section of subscribe. Then you can be sure that this.urlImg has a value.

.subscribe(
   url => this.urlImg = url,
   err => console.error('Request for URL failed: ' + err),
   () => {
      // operations when URL request is completed
   }
)
micaro
  • 946
  • 6
  • 10