简体   繁体   English

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

[英]Angular6/Typescript - ERROR when trying to Add Object to Array

I am failing to add a class into my Array. 我无法将一个类添加到我的数组中。 Error message: ERROR TypeError: Cannot read property 'value' of undefined 错误消息:ERROR TypeError:无法读取未定义的属性“值”

class

   export class Essensplan {

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

  }

service.ts 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'))
   );
  }

component 零件

  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();
      });
  }

Template** 模板**

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

It seems like it can not read an ID in the Text field, is it possible to convert the String (?) input into a number 似乎无法读取“文本”字段中的ID,是否可以将输入的字符串(?)转换为数字

your essensplanid.value is not defined, because in the input you wrote #Wochennummer. 您的essensplanid.value未定义,因为在输入中您编写了#Wochennummer。

just change essensplan.id to #Wochennummer or the other way 只需将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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM