如何在Angular 5+对象中向集合添加数据?

时间:2018-09-01 20:46:14

标签: javascript angular typescript asp.net-core-2.0

我正在尝试从TypeScript代码向对象内部的集合中添加数据。我已经从html绑定的视图中成功获取了nametype,所以我想知道如何在将新列表添加到数据库之前如何通过代码编辑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
}

1 个答案:

答案 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

只需进行这些更改,代码就可以工作。