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

问题描述 投票:0回答:1

我试图从我的TypeScript代码中将数据添加到我的集合中。我成功地从html绑定视图中获取nametype所以我想知道如何在将新列表添加到我的数据库之前通过代码编辑this.newList.socialData模型。

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

打字稿:

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
}
javascript angular typescript asp.net-core-2.0
1个回答
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

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

© www.soinside.com 2019 - 2024. All rights reserved.