如何清除Angular工时表模块提交时残留的旧数据?
问题根因
你的代码存在两个导致旧值残留的问题:
monObj/tueObj/wedObj/thursObj/friObj未在循环内部声明,作用域属于外层函数,且每次循环都没有重置初始值。当某一天的表单输入为空时,对应if分支不执行,变量会保留上一次循环/上一次提交时的旧值。- 不管五个日期对象是否有有效值,都统一全部推入
dayArr,导致旧值被带到最终payload中。
修复方案
核心调整点
- 每次循环开始时先重置所有日期对象的初始值为
null,清除上一轮残留值 - 仅将本次循环中确实赋值的有效对象推入
dayArr,如果业务要求空值也要传0小时,则统一给空的位置生成值为0的对象即可 - 把原有
var替换为let,使用块级作用域避免变量提升导致的作用域混乱
修复后代码示例
for (let i=0; i<counter; i++){ let dayArr = []; // 每次循环先重置所有日期对象,清除上一轮残留值 let monObj = null, tueObj = null, wedObj = null, thursObj = null, friObj = null; if (this.tform.value.timesheet[i].mon != null && this.tform.value.timesheet[i].mon != ''){ monObj = { workdate: arr[0].date, hoursspent: Number(this.tform.value.timesheet[i].mon) } } if (this.tform.value.timesheet[i].tue != null && this.tform.value.timesheet[i].tue != ''){ tueObj = { workdate: arr[1].date, hoursspent: Number(this.tform.value.timesheet[i].tue) } } if (this.tform.value.timesheet[i].wed != null && this.tform.value.timesheet[i].wed != ''){ wedObj = { workdate: arr[2].date, hoursspent: Number(this.tform.value.timesheet[i].wed) } } if (this.tform.value.timesheet[i].thur != null && this.tform.value.timesheet[i].thur != ''){ thursObj = { workdate: arr[3].date, hoursspent: Number(this.tform.value.timesheet[i].thur) } } if (this.tform.value.timesheet[i].fri != null && this.tform.value.timesheet[i].fri != ''){ friObj = { workdate: arr[4].date, hoursspent: Number(this.tform.value.timesheet[i].fri) } } // 仅把非空的有效对象推入数组 [monObj, tueObj, wedObj, thursObj, friObj].forEach(item => { if (item) dayArr.push(item); }); // 【可选:如果业务要求空值也要传0小时,替换上面的forEach逻辑为以下代码】 // dayArr = [ // monObj ?? {workdate: arr[0].date, hoursspent: 0}, // tueObj ?? {workdate: arr[1].date, hoursspent: 0}, // wedObj ?? {workdate: arr[2].date, hoursspent: 0}, // thursObj ?? {workdate: arr[3].date, hoursspent: 0}, // friObj ?? {workdate: arr[4].date, hoursspent: 0}, // ] let tmpPayloadObj = { timesheetId: this.tform.value.timesheet[i].timesheetId??0, projectid: this.tform.value.timesheet[i].project, taskid: this.tform.value.timesheet[i].task, dayListDetail: dayArr, totalHours: 0 } finalArr.push(tmpPayloadObj) }
内容的提问来源于stack exchange,提问作者Makizh
相关产品推荐
相关产品推荐

