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
相关产品推荐
相关产品推荐

