Как добавить данные в коллекцию в объекте Angular 5+? - PullRequest
0 голосов
/ 01 сентября 2018

Я пытаюсь добавить данные в мою коллекцию внутри объекта из моего кода TypeScript. Я успешно получаю name и type из представления в привязке html. Поэтому мне было интересно, как я могу отредактировать модель 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
}

1 Ответ

0 голосов
/ 02 сентября 2018

Полагаю, я просто хочу добавить новый элемент в массив 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

Просто внесите эти изменения, и код должен работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...