gpt4 book ai didi

angular - 带有空对象的补丁值

转载 作者:行者123 更新时间:2023-12-03 15:24:52 26 4
gpt4 key购买 nike

我正在使用 Angular 6 并且我正在尝试执行 patchValue 以使用来自可观察的 http 调用的数据填充我的表单。一切都很好,除了我有一个 secondaryPhone 值,该值可以是 null 填充可观察对象的 json。当它为空时,我收到错误“无法将未定义或空值转换为对象”。我知道如果每个值不为空,我可以单独手动修补它,但是有没有办法加载这个值而不必手动修补每个值?

模型.ts

export class UserInfoModel {
userId: number;
dob: Date;
firstName: string;
middleInitial: string;
lastName: string;
genderTypeId: number;
ssnLast4: string;
userAddresses: UserAddress[];
primaryPhone?: Phone;
secondaryPhone?: Phone;
fax?: Phone;
}

export class Address {
address1: string;
address2: string;
city: string;
stateCd: string;
zipCode: string;
internationalAddress: string;
countryId: number;
}

export class UserAddress {
userAddressId: number;
userId: number;
active: boolean;
address: Address;
}

export class Phone {
phoneId: number;
phoneTypeId: number;
phoneNumber: string;
internationalPhone: string;
}

组件.ts

this.as.accountUserInfo(this.activeRoute$.ActiveUserId).subscribe(data => {
this.userInfoModel$ = data as UserInfoModel;
this.userInfoForm.patchValue(this.userInfoModel$);
});

this.userInfoForm = this.fb.group({
'userId': ['', [Validators.required]],
'dob': [null, [Validators.required]],
'firstName': ['', [Validators.required, Validators.maxLength(50)]],
'middleInitial': ['', [Validators.maxLength(1)]],
'lastName': ['', [Validators.required]],
'genderTypeId': ['', [Validators.required]],
//TODO: Add conditional requirement
'ssnLast4': ['', [Validators.pattern("/^\d{4}$/")]],
userAddresses: this.fb.array([
this.fb.group({
'userAddressId': [''],
'userId': ['', [Validators.required]],
'active': ['', [Validators.required]],
address: this.fb.group({
'address1': ['', [Validators.required]],
'address2': ['', [Validators.required]],
'city': ['', [Validators.required]],
'stateCd': ['', [Validators.required]],
'zipCode': ['', [Validators.required]],
'internationalAddress': ['', [Validators.required]],
'countryId': ['', [Validators.required]]
})
})
]),
primaryPhone: this.fb.group({
'phoneId': [''],
'phoneTypeId': ['', [Validators.required]],
'phoneNumber': ['', [Validators.required]],
'internationalPhone': ['', [Validators.required]]
}),
secondaryPhone: this.fb.group({
'phoneId': [''],
'phoneTypeId': ['', [Validators.required]],
'phoneNumber': ['', [Validators.required]],
'internationalPhone': ['', [Validators.required]]
})
});

JSON 示例

{
"userId": 6,
...,
"primaryPhone": {
"phoneId": 2,
"phoneTypeId": 2,
"phoneNumber": "3030303303",
"internationalPhone": ""
},
"secondaryPhone": null
}

最佳答案

在我们等待的同时this issue待解决,改null修补前清空对象的值:

this.form.patchValue({
...data,
secondaryPhone: data.secondaryPhone || {}
})

关于angular - 带有空对象的补丁值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51866061/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com