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

如何将Angular循环生成的多组表单数据按数组格式提交给API

解决方案

你现在的核心问题是所有表单项都绑定了全局的单值变量,循环渲染时后一项会覆盖前一项的输入值,只能拿到最后一条数据。按以下两步修改即可:

1. 修改 product.page.html 代码

把双向绑定直接关联到循环体内部的product实例,避免共用全局变量:

<details *ngFor="let product of products;">
    <summary>{{product.name}}</summary>
    <ion-input type="text" [(ngModel)]="product.categoryId"></ion-input>
    <ion-input type="text" [(ngModel)]="product.id"></ion-input>

    <ion-row>
        <ion-col>
            <ion-input type="text" [(ngModel)]="product.minPrice"></ion-input>
        </ion-col>

        <ion-col>
            <ion-input type="text" [(ngModel)]="product.maxPrice"></ion-input>
        </ion-col>
    </ion-row>
    <ion-row>
        <ion-col>
            售卖状态:
            <ion-select [(ngModel)]="product.forSale" interface="popover">
                <ion-select-option value="0">否</ion-select-option>
                <ion-select-option value="1">是</ion-select-option>
            </ion-select>
        </ion-col>
    </ion-row>
</details>
<ion-button type="button" (click)="saveDetails()">保存</ion-button>

注:原本的value属性可以直接删除,[(ngModel)]双向绑定会自动把product的初始值填充到输入框中。

2. 修改 product.page.ts 代码

删除原来的全局单值变量,提交时直接遍历products数组构造要求的格式:

...
// 原来的categoryId/productId等5个单值变量可以全部删除

saveDetails() {
    // 构造符合API要求的请求参数
    const requestData = {
        productList: this.products.map(item => ({
            categoryId: item.categoryId,
            productId: item.id,
            minPrice: item.minPrice,
            maxPrice: item.maxPrice,
            forSale: item.forSale
        }))
    };

    this.http.post('http://example.com/api/saveDetails', JSON.stringify(requestData))
    .subscribe((res: any) => {console.log("提交成功");});
}

如果你的products数组原本就只有这5个需要提交的字段,也可以直接简写为productList: this.products,不需要额外用map过滤。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:45:00