Angular 2 - 从 FormArray 创建对象数组



我有一个包含FormArray人员的表单。然后,人员数组包含一个地址的 FormArray,它为我提供了以下 JSON:

{
"people": [
{
"lastName": "Last-1",
"firstName": "First-1",
"middleName": "",
"addresses": [
{
"street": "Person1 - Address1"
},
{
"street": "Person1 - Address2"
}
]
},
{
"lastName": "Last-2",
"firstName": "Last-2",
"middleName": "",
"addresses": [
{
"street": "Person2 - Address1"
}
]
}
]
}

现在我正在尝试从表单中获取这些"人"并创建一个 Person 对象数组

export class ReportPerson {    
lastName: string = '';
firstName: string = '';
middleName: string = ''; 
addresses: PersonAddress[];
}
export class PersonAddress {
street: string = '';   
}

当我使用 console.log(form.get('people'(.value(;我得到以下结果:

(2) [{…}, {…}]0: {lastName: "Last-1", firstName: "First-1", middleName: "", 
addresses: Array(2)}
1: {lastName: "Last-2", firstName: "Last-2", middleName: "", 
addresses: Array(1)}length: 2__proto__: Array(0)

但是无论我如何尝试获取数据,它都说我的列表是未定义的。例如,以下内容返回它无法读取未定义的"lastName"。

save(form: any) {
var reportPersonList: ReportPerson[] = new Array();
var people = form.get('people');
for (let i = 0; i < people.length; i++) {
console.log(people[i].lastName);
}
}
} 

我的问题是,从 FormArray 中的数据创建人员对象数组的正确语法是什么?我知道这是我缺少的基本知识,但是我已经习惯了C#,并且不熟悉Typescript/Angular2。

对于遇到此问题的任何其他人,我能够通过从"people"表单数组的值创建一个新的表单数组来解决它。然后使用表单数组函数将表单值映射到对象值。然后,我对地址数组重复了该过程。

save(form: any) {
var reportPersonList: ReportPerson[] = new Array();
var people = form.get('people') as FormArray;
for (let i = 0; i < people.length; i++) {
var p = new ReportPerson;
p.lastName = people.at(i).get('lastName').value;
p.firstName = people.at(i).get('firstName').value;
p.middleName = people.at(i).get('middleName').value;
var addresses = people.at(i).get('addresses') as FormArray;
for (let j = 0; j < addresses.length; j++) {
var a = new PersonAddress;
a.street = addresses.at(j).get('street').value;
p.addresses.push(a);
};
reportPersonList.push(p);
}
this.reportFormDataService.setReportPeople(reportPersonList);
}

很高兴你让它工作了!

以为我会发布我会如何做到这一点。

let json = {
"people": [
{
"lastName": "Last-1",
"firstName": "First-1",
"middleName": "",
"addresses": [
{
"street": "Person1 - Address1"
},
{
"street": "Person1 - Address2"
}
]
},
{
"lastName": "Last-2",
"firstName": "Last-2",
"middleName": "",
"addresses": [
{
"street": "Person2 - Address1"
}
]
}
]
}
// for each person in the array, return a class instantiate
json.people.map(person => {
return new Person().deserialize(person);
});
// 
class Person(){
public lastName: string;
public middleName: string;
public firstName: string;
public addresses: Array<any>
constructor(){
this.addresses = new Array<string>();
}
// note you could of just used the constructor,
// but its a personal preference to have a serialize and deserialize for data coming from the server in a json object type.
deserialize(data: any){
this.lastName = data.lastName;
this.firstName = data.firstName;
this.middleName = data.middleName;
this.addresses = data.addresses;
}
}

相关内容

  • 没有找到相关文章

最新更新