我正在尝试从TypeScript代码向对象内部的集合中添加数据。我已经从html绑定的视图中成功获取了name
和type
,所以我想知道如何在将新列表添加到数据库之前如何通过代码编辑this.newList.socialData
模型。 / p>
HTML:
<mat-form-field>
<input matInput placeholder="List Name" [(ngModel)]="newList.name" name="name" type="text" class="form-control rounded-0" required>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="List Type" [(ngModel)]="newList.type" name="type" type="text" class="form-control rounded-0" required>
</mat-form-field>
<button (click)="addList()" type="button" class="btn btn-primary float-right">Create New</button>
声明:
newList: List = {} as List
TypeScript:
addList() {
let tt = {} as SocialData;
//tt.socialId = 'jj'
//this.newList = {} as List;
// I would like to add test data to socialData here
this.newList.socialData.push(tt);
this.listService.addList(this.newList)
.subscribe(
res => {
this.fetchLists();
},
err => console.log(err)
)
}
型号:
export class List {
name: String;
type: String;
inputValue: String;
socialData: [SocialData]
}
export class SocialData {
socialId: String
}
答案 0 :(得分:1)
我想只是想向socialData数组添加一个新项目。
您需要在代码中进行2次更改:
1.声明
export class List {
name: String;
type: String;
inputValue: String;
// socialData: [SocialData]; // This is wrong
socialData: SocialData[]; // declares a type of array
constructor() {
this.socialData = []; // Initialize the array to empty
}
}
2。创建实例:
// let tt = {} as SocialData; // This will just cast an empty object into List
newList: List = new List(); // Will create an instance of List
只需进行这些更改,代码就可以工作。