You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Firebase Storage:等待图片上传完成后返回downloadURL

问题解决方法

你的核心问题是saveCanvas虽标记为async,但内部Firebase上传与URL获取逻辑未正确返回等待完成的Promise,导致onSubmit里的.then()会在上传未完成、URL未获取时就执行,最终report.signature可能为空。

修改后的代码如下:

async saveCanvas(): Promise<string> {
  const loading = await this.loadingController.create();
  await loading.present();
  
  const signature = this.signaturePad.toDataURL().slice(22);
  this.signaturePhotoName = new Date().toJSON();
  const fileStoragePath = `signatures/${this.signaturePhotoName}`;
  const imageFireStorageReference = this.angularFireStorage.ref(fileStoragePath);
  
  return new Promise((resolve, reject) => {
    this.fireUploadTask = imageFireStorageReference.putString(signature, 'base64', { contentType: 'image/png'});
    
    this.fireUploadTask.snapshotChanges().pipe(
      finalize(async () => {
        try {
          const url = await imageFireStorageReference.getDownloadURL().toPromise();
          this.uploadedSignaturePhotoPath = url;
          this.report.signature = url;
          this.reportForm.get('_signature').setValue(url);
          await loading.dismiss();
          resolve(url);
        } catch (error) {
          await loading.dismiss();
          reject(error);
        }
      })
    ).subscribe({
      error: async (err) => {
        await loading.dismiss();
        reject(err);
      }
    });
  });
}

async onSubmit() {
  if (!this.isCanvasBlank()) {
    try {
      await this.saveCanvas();
      if (this.report.signature) {
        if (this.reportForm.valid) {
          this.reportsService.postReport(this.report).subscribe(response => {
            console.log(response);
          });
        } else {
          console.log("需要补充更多信息");
        }
      }
    } catch (error) {
      console.error("上传失败:", error);
    }
  } else {
    alert("请签署签名!");
  }
}

关键改动说明:

  • saveCanvas返回Promise<string>,确保仅在URL成功获取后才resolve,上传或URL获取失败则reject
  • 用toPromise()将getDownloadURL()的Observable转为Promise,避免嵌套订阅
  • 在finalize和订阅的error回调中统一处理loading关闭与错误抛出
  • onSubmit改用await替代.then(),逻辑更清晰,同时捕获上传过程中的错误
  • 移除重复创建imageFireStorageReference的冗余代码

修改后,onSubmit内的逻辑只会在签名上传完成、URL成功获取后执行,不会再出现需多次点击或等待的问题。

内容的提问来源于stack exchange,提问作者lumash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 12:06:13