Angular表单输出对象转时间数组问题求助
解决方案
场景1:将提交请求体body中的时间字段转为数组
如果需要把表单里的hour_start和minute_start合并成数组存入请求体,在onSubmit方法中处理:
onSubmit(): void { this.error$.next(""); const formValue = this.form.value; // 转换为数字并组成数组,空值时设为0避免出现NaN const timeArray = [ parseInt(formValue.hour_start || '0', 10), parseInt(formValue.minute_start || '0', 10) ]; // 构造请求体,可选择替换原有字段或新增数组字段 const body: ActuatorBody = { ...formValue, id: this.data.element?.id, timeArray: timeArray // 若不需要原hour_start、minute_start字段,可添加: // delete body.hour_start; // delete body.minute_start; }; if (this.manualState && this.selectedTiming.value === 'manual') { body.manual_state = this.manualState.value; } this.setService.editActuator(body) .pipe(map((id: string) => id.toString()), take(1)) .subscribe({ next: (id: string) => { const auto = (this.data.element) ? this.data.element.automatic_state : false; const result: DialogResult<TableElement> = { message: "تنظیمات ذخیره شد.", succeed: true, data: this.createTableElement(id, body, auto) } console.log(body); this.close(result); }, error: (err: any) => { console.error(err); this.error$.next(err.message); } }); }
场景2:将createTableElement中的cronValues改为数组格式
如果要把返回的TableElement里的cronValues从对象转为数组,修改createTableElement方法:
private createTableElement(id: string, body: ActuatorBody, automatic_state: boolean) { const sections = body.sections.map((section) => section.number); // 转换小时和分钟为数字,空值设为0 const hour = parseInt(this.hourStart?.value || '0', 10); const minute = parseInt(this.minuteStart?.value || '0', 10); return { id: id, name: body.name, organ_id: this.selectedOrgan, application_id: this.selectedApp.id, application_name: this.selectedApp.name, type_id: this.selectedType.id, type: this.selectedType.name, manual_state: body.manual_state ? body.manual_state : false, state_timing: { value: this.selectedTiming.value, name: this.selectedTiming.name }, // 替换为数组格式 cronValues: [hour, minute], sections: sections } as TableElement; }
关键注意事项
- 类型转换:即使input设置了
type="number",FormControl返回的值仍可能是字符串,必须用parseInt转成数字,才能得到[12,10]而非['12','10']。 - 空值处理:添加
|| '0'避免字段为空时出现NaN,保证数组始终是有效数字数组。
内容的提问来源于stack exchange,提问作者Rezvaneh Aftabgard
相关产品推荐
相关产品推荐

