问题描述
在我的 angular 6 应用程序中,有一个配置文件更新部分,配置文件表单最初加载预填充的详细信息,即注册期间保存的详细信息。
表格如下图
如果触摸新电子邮件地址为必填项,如果输入新电子邮件地址为必填项。
在提交时,调用后端服务来更新用户配置文件。如果此服务关闭,我必须将更改后的表单字段恢复为最初加载的方式。
我正在使用以下代码重置电子邮件、确认电子邮件、手机号码和白天的电话号码。
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();
}
});
}