【问题标题】:Waiting for observable to finish - Angular等待可观察完成 - Angular
【发布时间】:2019-03-25 20:39:31
【问题描述】:

我正在使用 Angular 和 Firebase 存储来上传图像,当我尝试在 tap 内的 console.log 中打印时,我遇到了问题,我的 urlImg 是 undefined。

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

【问题讨论】:

  • tap 将在finalize 之前发生,因为finalize 是最后发生的事情
  • @user184994 哦,我不是那个!有什么建议?关于如何解决这个问题?
  • 这取决于你真正想要做什么。如果需要,您显然可以从 subscribe 中访问 this.urlImg?
  • 我想等待文件上传,然后在 Firebase 存储中获取图像的 url,然后将位于 Firebase 存储中的图像的 url 上传到 firestore @user184994

标签: angular firebase rxjs google-cloud-firestore observable


【解决方案1】:

另一种选择是利用已完成的订阅部分。那么就可以确定 this.urlImg 有值了。

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

【讨论】:

    猜你喜欢
    • 2018-01-03
    • 2017-10-12
    • 2017-09-08
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多