首页 > 解决方案 > 使用 Angular 6 更新表单值时出现延迟

问题描述

我注意到,当我尝试在FormBuilder使用 HTTPclient 提交之前更新右侧的几个值时,我的值没有更新。当我第二次运行提交时,这些值会更新。

private mergeDates(dateValue: string, timeValue: string): string {
  const returnValue = dateValue.toString().replace(' 00:00', ` ${timeValue}`);
  return returnValue;
}

private submitVacancy() {
  if (this.vacancyForm.invalid) {
    return;
  }
  const fValue = this.vacancyForm.value;
  const fControls = this.vacancyForm.controls;
  fControls['beginDateTime'].setValue(
    this.mergeDates(fValue['beginDate'], fValue['beginTime']),
  );
  fControls['endDateTime'].setValue(
    this.mergeDates(fValue['beginDate'], fValue['endTime']),
  );
  alert(JSON.stringify(fValue));
  this.http.post(`${this.apiUri}/addvacancy`, JSON.stringify(fValue));
}

标签: angularformsangular6angular-reactive-formsformbuilder

解决方案


我像 Mateusz 建议的那样在我的代码中添加了以下行,现在它可以正常工作了。我的代码现在看起来像这样。

private mergeDates(dateValue: string, timeValue: string): string {
  const returnValue = dateValue.toString().replace(' 00:00', ` ${timeValue}`);
  return returnValue;
}
private submitVacancy() {
  if (this.vacancyForm.invalid) {
    return;
  }

  const fControls = this.vacancyForm.controls;
  let fValue = this.vacancyForm.value;

  fControls['beginDateTime'].setValue(
    this.mergeDates(fValue['beginDate'], fValue['beginTime']),
  );

  fControls['endDateTime'].setValue(
    this.mergeDates(fValue['beginDate'], fValue['endTime']),
  );

  fValue = this.vacancyForm.value;
  alert(JSON.stringify(fValue));
  console.log(JSON.stringify(fValue));
  this.http.post(`${this.apiUri}/vacancy`, JSON.stringify(fValue));
}

fValue = this.vacancyForm.value;在运行我的setValue().


推荐阅读