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

Angular-14中HttpProgressEvent对象可能为undefined错误如何解决?

解决Angular 14中"Object is possibly 'undefined'"错误

错误原因

Angular 14默认启用TypeScript严格空值检查,HttpClient返回的事件对象可能为undefined,同时直接访问event.loaded、event.total时,TypeScript无法确认这些属性一定存在,触发空值检查警告。

修复后的代码

download = () => {
  this.mandateService.getMandateDocument(this.documentId).subscribe((event) => {
    // 先判断event是否存在,避免后续逻辑访问undefined
    if (!event) return;

    if (event.type === HttpEventType.UploadProgress) {
      // 检查total和loaded的有效性,避免除以0或undefined
      if (event.total && event.loaded >= 0) {
        this.progress = Math.round((100 * event.loaded) / event.total);
      }
    } else if (event.type === HttpEventType.Response) {
      this.message = 'Download success.';
      this.downloadFile(event);
    }
  });
};

关键修复点

  • 空值守卫:添加if (!event) return;,确保后续逻辑仅在event存在时执行
  • 属性有效性校验:计算进度前判断event.total是否存在且不为0,避免计算错误和类型警告
  • (可选)若getMandateDocument返回明确类型(比如Observable<HttpEvent<Blob>>),可给event添加类型注解,让TypeScript更精准推断类型:
    this.mandateService.getMandateDocument(this.documentId).subscribe((event: HttpEvent<Blob>) => {
      // 后续逻辑不变
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:55:17