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

Angular4中传递Typescript Map通过POST请求后端收到空对象问题

错误原因

  • 核心原因是JSON序列化规则不支持ES6 Map结构:JSON.stringify()处理Map对象时,不会读取Map内部存储的键值对,只会返回空对象{}。你使用的HTTP客户端发送请求前会默认将请求体序列化为JSON格式,因此后端收到的queries字段就是空值。
  • TypeScript类型定义仅作用于编译阶段:你声明的queries!: Map<string, string[]>只是编译期的类型校验,不会在运行时自动将Map转为后端可识别的结构。

修复方案

方案1:直接用普通对象替代Map(推荐)

后端要求的Map<String, List<String>>对应前端JSON结构就是普通的键值对对象,直接用Record类型定义即可,不需要用Map:

  1. 先修改接口定义:
// 原定义:queries!: Map<string, string[]>
// 修改为:
queries!: Record<string, string[]>
  1. 调整业务代码:
let x = this.searchName
let y = this.searchValue
const queries = {} as Record<string, string[]>
queries[x] = [y]
this.SearchDto.queries = queries
this._filterSer.searchAgg(this.SearchDto).subscribe((res) => {})

方案2:保留Map逻辑,序列化前手动转换

如果业务逻辑中需要用到Map的API,就在发送请求前将Map转为普通对象:

// Map转普通对象工具方法
function mapToObj(map: Map<string, string[]>) {
  const res: Record<string, string[]> = {}
  map.forEach((val, key) => res[key] = val)
  return res
}

// 发送请求前转换结构
const reqDto = {
  ...this.SearchDto,
  queries: mapToObj(this.SearchDto.queries)
}
this._filterSer.searchAgg(reqDto).subscribe((res) => {})

注:SpringBoot等Java后端框架可直接将符合结构的普通JSON对象反序列化为Map<String, List<String>>,无需额外适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:36:02