Angular14中如何将对象数组转为表单编码格式用于POST请求
Angular 14 实现带索引的表单编码参数 POST 请求
问题背景
在Angular 14应用中,需要向指定URL POST符合特定格式的表单编码参数,参数键需包含从零开始的行索引n,格式要求如下:
ItemNo[n]=<Item Identifier> Description[n]=<Item Identifier>
3个项的示例格式:
ItemNo[0]=1001 Description[0]=a wonderful item ItemNo[1]=1002a Description[1]=something ItemNo[2]=1002c Description[2]=another thing
待处理的数据源为以下对象数组:
[ { ItemNo: '1001', Description: 'a wonderful item' }, { ItemNo: '1002a', Description: 'something' }, { ItemNo: '1002c', Description: 'another thing' }, ]
此前尝试自行编写索引处理函数转换参数,但始终无法生成正确的键值对,同时对http.post()的参数类型存在疑惑。
解决方案
最终通过直接遍历数组构建HttpParams的方式解决问题,核心处理函数如下:
doFormParams(items: any[]): HttpParams { let params = new HttpParams(); items.forEach((item, index) => { for(const key in item){ params = params.append(`${key}[${index}]`, `${item[key]}`); } }); return params; }
在实际请求中,需配合设置表单编码类型的请求头:
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http'; // ... constructor(private http: HttpClient) {} submitItems(items: any[]) { const headers = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }); const formParams = this.doFormParams(items); return this.http.post('你的目标URL', formParams, { headers }); }
补充说明
虽然JSON格式是当前接口交互的更优选择,但由于第三方接口固定要求该表单编码格式,因此采用此方案。
内容的提问来源于stack exchange,提问作者Ego Placebo
相关产品推荐
相关产品推荐

