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

Spring Boot+Angular带参导出PDF时lotNum参数为undefined问题

Angular调用Spring Boot导出PDF参数异常修复方案

你遇到的lotNum=undefined问题本质是参数传值链路断裂,叠加代码里多处配置错误会导致导出功能完全失效,按以下步骤修复即可:


1. 优先修复参数为undefined的问题

  • 检查所有调用前端exportPdf方法的入口(按钮点击事件、表单取值、路由传参逻辑),必须传入实际赋值的lotNum有效值,禁止无参调用、传入未初始化变量。最常见的错误是模板里写了(click)="exportPdf()"没传参,或者绑定的lotNum变量名拼写错误。
  • 优化service层参数拼接逻辑,过滤无效参数,同时删除错误的请求头配置:
// service.ts 修正后代码
exportPdf(lotNum: string | null): Observable<Blob>  {
  let params = new HttpParams();
  // 仅当lotNum有非空有效值时才拼接请求参数
  if (lotNum) {
    params = params.append('lotNum', lotNum);
  }
  // 移除错误的请求头:Access-Control-Allow-Origin是后端响应头,前端不需要设置;responseType是请求配置项不是头字段;导出二进制不需要application/json头
  const headers = new HttpHeaders();
  return this.http.get("http://localhost:8080/export/pdf", {
    headers: headers,
    params: params,
    responseType: 'blob'
  });
}

2. 修复后端响应头拼写错误

后端Controller里的响应头名存在拼写错误,会导致浏览器无法识别文件下载规则,修正如下:

// 原错误写法:headers.add("Content-Dispositon", "inline; filename=simulation.pdf");
// 修正拼写,按需选择inline(预览)或attachment(直接下载)
headers.add("Content-Disposition", "attachment; filename=simulation.pdf");

3. 优化前端文件下载逻辑

原有Blob处理逻辑存在兼容性问题,且缺少错误捕获,修正simulation.ts代码如下:

// simulation.ts 修正后代码
exportPdf(lotNum: string | null){
  this.date = new Date();
  const latest_date = this.datepipe.transform(this.date, 'yyyy-MM-dd');
  this.simulationService.exportPdf(lotNum).subscribe({
    next: (blob: Blob) => {
      // 直接使用HttpClient返回的Blob对象即可,不需要重复包装
      if (window.navigator && (window.navigator as any).msSaveOrOpenBlob){
        (window.navigator as any).msSaveOrOpenBlob(blob, `simulation${latest_date}.pdf`);
        return;
      }
      const data = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = data;
      link.download = `simulation${latest_date}.pdf`;
      // 兼容低版本浏览器需要插入DOM才能触发点击
      document.body.appendChild(link);
      link.click();
      setTimeout(() => {
        window.URL.revokeObjectURL(data);
        link.remove();
      }, 100);
    },
    error: (err) => {
      // 可自定义错误提示,比如后端返回409状态码时提示数据校验不通过
      console.error('PDF导出失败', err);
    }
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 03:36:17