Waiting for observable to finish - Angular

送分小仙女□ 提交于 2020-01-25 08:28:05

问题


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:


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


来源:https://stackoverflow.com/questions/52918032/waiting-for-observable-to-finish-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!