Захват значения id из наблюдаемого - угловой - PullRequest
0 голосов
/ 22 октября 2018

У меня проблемы с проектом Angular.Я работаю со списком элементов, которые являются объектами JSON с id: номер и имя: любой.Список появляется, когда я щелкаю на типе настройки из другого списка, скажем, «Типы запросов».Я хочу добавить в список.Однако я также хочу удалить элементы из списка, и когда я добавляю новый элемент, мне нужно перейти к следующему номеру после последнего использованного номера идентификатора, а не к числу строк. Я пытаюсь отправить изменения вбэк-эндПрямо сейчас, когда я пытаюсь добавить элемент, я получаю следующую ошибку: «Экземпляр« Тип запроса »недопустим. Детали:« id »не может быть пустым (значение: undefined);« name »не может»быть пустым (значение: не определено). "Я провел некоторые исследования наблюдаемых в Angular, но я просто не могу точно определить проблему.Любая помощь будет оценена.

Вот код:

export class SettingsPage {
  items: any[];
  selectedItem: any;
  addTable: boolean = false;
  rows: {id:number, name:any}[] = [];
  editing = {};
  nameOld;
  editRow = {};
  rowCount: number;
  nameNew;
  wasClicked = false;

  @ViewChild("name") name: ElementRef;

  constructor(public navCtrl: NavController, public navParams: NavParams, 
  public alertCtrl: AlertController, private requestTypeApi : 
  RequestTypeApi, private requestSizeApi : RequestSizeApi, private 
  requestStatusApi : RequestStatusApi, private businessAreaApi : 
  BusinessAreaApi, private businessValueApi : BusinessValueApi, private 
  projectTypeApi : ProjectTypeApi, private projectTeamApi : ProjectTeamApi) 
  {
    this.items = [{label:"Request Types", service: this.requestTypeApi}, 
    {label: "Request Sizes", service: this.requestSizeApi}, {label: "Request 
    Status", service: this.requestStatusApi}, {label: "Business Areas", 
    service: this.businessAreaApi}, {label: "Business Values", service: 
    this.businessValueApi}, {label: "Project Types", service: 
    this.projectTypeApi}, {label: "Project Teams", service: 
    this.projectTeamApi}];
    this.selectedItem = navParams.get('items');
  }

  ionViewDidLoad() {
  }

  itemTapped(item) {
    this.selectedItem = item;
    this.selectedItem.wasClicked = true;
    console.log(this.selectedItem);
    this.addTable = true;
    this.selectedItem.service.find()
      .subscribe(data => {
        this.rows = data;
        this.rowCount = this.rows.length;
    });
  }

  cancelTapped() {
    this.addTable = false;
  }

  addTapped(event, cell, rowIndex) {
    const prompt = this.alertCtrl.create({
      title: 'Add Detail',
      inputs: [
        {
          name: 'name'
        }
      ],
      buttons: [
        {
          text: 'Save',
          handler: data => {
            var detail = data.name;
            this.rowCount = this.rowCount + 1;

            this.selectedItem.service.create().subscribe(result => {
              this.rows.push({id: this.rowCount, name: detail});
            });
            this.rows = this.rows.slice();
          }
        },
        {
          text: 'Cancel'
        }        
      ]
    });
    prompt.present();
  }

  save(event) {
    this.nameNew = '';
    this.nameNew = event.target.value;
    this.selectedItem.service.updateAttributes(this.rowCount, 
    this.name).subscribe(result => {
      let rows = this.rows;
      rows[this.rowCount] = Object.assign({}, { id: 
      this.rows[this.rowCount].id, name: this.nameNew != "" ? this.nameNew : 
      this.nameOld }),
      this.rows = [...this.rows];
      this.rows.push({id: this.rowCount, name: this.name});
    })
  }

  storeOldValues(rowIndex) {
    this.nameOld = this.rows[rowIndex].name;
    this.editRow = rowIndex;
    setTimeout(() => this.name.nativeElement.focus(), 50);
  }

  doneEditing(rowIndex, returnOld) {
      if (returnOld) {
        this.rows[rowIndex].name = this.nameOld;
      } else { 
        this.rows[rowIndex].name = this.nameNew;
    }
    this.editRow = null;
  }

  deleteRow(rowIndex) {
    let temp = [...this.rows]
    temp.splice(rowIndex, 1);
    this.rows = temp;
  }
}
...