Angular6 / Typescript-尝试将对象添加到数组时出错

时间:2018-09-12 10:50:25

标签: arrays angular function typescript

我无法将一个类添加到我的数组中。错误消息:ERROR TypeError:无法读取未定义的属性“值”

   export class Essensplan {

   id: number;
   EssenProWoche: number[] = new Array(5);

  }

service.ts

 / POST: add a new essensplan to the server */
  addEssensplan(essensplan: Essensplan): Observable<Essensplan> {
    return this.http.post<Essensplan>(this.essensplanUrl, essensplan, 
httpOptions).pipe(
      tap((essensplan: Essensplan) => this.log(added essen w/ 
id=${essensplan.id})),
      catchError(this.handleError<Essensplan>('addEssensplan'))
   );
  }

组件

  addEssensplan(id: number): void {
    // id = id.trim();
    if (!id) { return; }
    this.essensplanService.addEssensplan({ id } as Essensplan)
      .subscribe(essensplan => {
        this.essensplan.push(essensplan);
        this.changeDetector.markForCheck();
      });
  }

模板**

<div>
  <label>Essensplan Woche:
<input type=number #Wochennummer />
  </label>
  <!-- (click) passes input value to add() and then clears the input -->
  <button (click)="addEssensplan(essensplanid.value); essensplanid.value=''">
    add
  </button>

似乎无法读取“文本”字段中的ID,是否可以将输入的字符串(?)转换为数字

1 个答案:

答案 0 :(得分:1)

您的essensplanid.value未定义,因为在输入中您编写了#Wochennummer。

只需将essensplan.id更改为#Wochennummer即可

<div>
 <label>Essensplan Woche:
    <input type="number"  #Wochennummer />
  </label>
  <!-- (click) passes input value to add() and then clears the input -->
  <button (click)="addEssensplan(Wochennummer.value); Wochennummer.value=''">
   add
   </button>
</div>