Angular 6 - 在提交时还原表单字段更改的值

问题描述

在我的 angular 6 应用程序中,有一个配置文件更新部分,配置文件表单最初加载预填充的详细信息,即注册期间保存的详细信息。

表格如下图

enter image description here

标题、名字、姓氏、电子邮件地址是输出字段,因此无法编辑。

如果触摸新电子邮件地址为必填项,如果输入新电子邮件地址为必填项。

用户可以编辑新的电子邮件地址、手机号码和白天电话号码字段。

在提交时,调用后端服务来更新用户配置文件。如果此服务关闭,我必须将更改后的表单字段恢复为最初加载的方式。

我正在使用以下代码重置电子邮件、确认电子邮件、手机号码和白天的电话号码。

updateProfile(){
    this.http.post('https://testurl/user/updateProfile',param,options).subscribe(
        data => {
            console.log("Profile update successful:",data);
        },error => {
            console.log("Profile update error!",error);
            if(error.status === '500'){ // If service is down
                this.profileForm.controls['newemail'].reset();
                this.profileForm.controls['confirmemail'].reset();
                this.profileForm.controls['mobile'].reset();
                this.profileForm.controls['daytimephone'].reset();          
            }
        }
    );
}

但这会导致以下错误。无论如何,重置只会清空字段。

ERROR TypeError: Cannot read property 'reset' of undefined

我想查找字段是否被修改,如果存在,则将它们的值恢复为初始值。

为了更清楚,假设用户修改了以下字段

new email => testabc10@gmail.com
confirm email => testabc10@gmail.com
Daytime Phone => +44123456789

假设后端关闭,提交此表单时,如何取回白天电话号码的初始值?

请指导,谢谢

解决方法

我想您有一种方法可以设置控件的初始值。可能就在加载配置文件之后。如果 Web 请求失败,则调用相同的方法似乎是个好主意。

profile: Profile;

setProfileFormValue() {
   this.profileForm.controls['newemail'].setValue('');
   this.profileForm.controls['confirmemail'].setValue('');
   this.profileForm.controls['mobile'].setValue(this.profile.mobile);
   this.profileForm.controls['daytimephone']
      .setValue(this.profile.daytimephone);
}
updateProfile() {
   this.http.post('https://testurl/user/updateProfile',param,options)
      .subscribe(data => {
         console.log("Profile update successful:",data);
      },error => {
         console.log("Profile update error!",error); // console.error instead of console.log?
         if(error.status === '500') { // If service had an internal server error (not necessary down)
            this.setProfileFormValue();
         }
      });
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...