Waiting for observable to finish - Angular

2019-08-28 19:55发布

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);
        }
      })
    );

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-28 20:17

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
   }
)
查看更多
登录 后发表回答