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

Angular 4父子组件关系:表单提交后构造期望db.json结构问题

解决Angular 4表单提交生成指定JSON结构的问题

嘿,我来帮你调整代码,让表单提交后生成你想要的db.json结构!首先先明确我们的目标结构:

{ 
  "id": 0, 
  "code": "string", 
  "name": "string", 
  "isActive": true, 
  "questionerdetails":[ 
    { "id":0, "questiondetail": "string", "isActive": true } 
  ] 
}

现有代码问题分析

从你给出的代码片段来看,目前只是往this.questions里push空的questiondetail对象,没有关联表单实际输入值,也没构建完整的嵌套结构,缺少id、isActive这些必填字段,更没有把基础问卷信息和问题详情组合成最终的目标对象。

修改后的完整formSubmits方法

下面是调整后的代码,我会在注释里说明每一步的作用:

formSubmits() { 
  this.validate = true; 
  this.preProcessConfigurations(); 

  // 1. 获取表单中的基础问卷信息
  const baseQuestioner = this.questionerForm.value;

  // 2. 构建最终的问卷对象,补充默认值(id可以根据需求改成自增或唯一值,这里按示例用0)
  const finalQuestioner = {
    id: 0, // 如果需要动态生成唯一id,可以用Date.now()或者自定义计数器
    code: baseQuestioner.code,
    name: baseQuestioner.name,
    isActive: true, // 若表单有复选框控制该状态,可改成baseQuestioner.isActive
    questionerdetails: []
  };

  // 3. 遍历子组件的问题列表,构建每个问题详情对象
  this.allquestionare.forEach((obj, index) => {
    // 假设obj包含用户输入的问题内容,实际属性名请根据你的子组件传值调整
    const questionDetail = {
      id: index, // 用索引作为id,或改成固定值/自定义唯一标识
      questiondetail: obj.questiondetail || '', // 确保拿到实际输入的内容
      isActive: true
    };
    finalQuestioner.questionerdetails.push(questionDetail);
  });

  // 现在finalQuestioner就是完全符合要求的结构了
  console.log('最终生成的结构:', finalQuestioner);

  // 这里可以添加提交到后端或写入db.json的逻辑,比如:
  // this.http.post('/api/questioner', finalQuestioner).subscribe(res => {...});
}

关键注意事项

  • 子组件数据关联:确保this.allquestionare数组里的每个元素都包含用户实际输入的questiondetail值,如果是父子组件传值,需要在子组件中通过@Output或共享服务把输入内容传递给父组件。
  • id生成优化:示例里用了固定值和索引作为id,如果需要全局唯一标识,建议用Date.now()或者第三方库生成唯一id,避免重复。
  • 状态灵活控制:如果isActive是由表单复选框控制的,直接替换成baseQuestioner.isActive即可,不用硬编码true。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:55:18