首页 > 解决方案 > Angular 5 模型到对象以用于发布请求

问题描述

我有以下问题。我想从表单中加载数据并通过邮寄方式发送。我收到以下错误消息:'ERROR TypeError: Can not set property'barcode'of undefined'

我的蔑视是 item.barcode 是未知的。虽然我创建了一个 Item 类型的对象。

这是我的 HTML 代码

<form class="item-form">
  <mat-form-field>
    <input matInput name="barcode" placeholder="Barcode" value="IN SH " [(ngModel)]="barcode">
  </mat-form-field>

  {{barcode}}
<br>
  <mat-form-field>
    <input matInput name="itemName" placeholder="Item Name" [(ngModel)]="name">
  </mat-form-field>
  <br>

  <mat-form-field>
      <textarea matInput name="description" placeholder="Beschreibung" matTextareaAutosize matAutosizeMinRows="2"
                matAutosizeMaxRows="5" [(ngModel)]="description"></textarea>
    </mat-form-field>

    <br>
    <button mat-raised-button color="green" (click)='onSubmit()'>Item speichern</button>
</form>

这是我的组件 TS 代码

public item: Item;
  public barcode: string;
  public name: string;
  public description: string;

  constructor(public itemFormService: ItemFormService) {

  }

  ngOnInit() {


  }

  onSubmit() {
    console.log('onSubmit in Item Form Component');
    this.item.barcode = this.barcode;
    this.item.name = this.name;
    this.item.description = this.description;

    console.log(this.item);
    this.itemFormService.addItem(this.item);
  }

这是我的服务 TS 代码

  constructor(public http: HttpClient) { }

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json'
    })
  };

  addItem(item: any) {
    return this.http.post('', item, this.httpOptions).subscribe(
      (result) => {
        console.log(result);
      }
    );
  }

标签: angularpostundefinedangular5

解决方案


目前,虽然您的item字段已声明,但尚未初始化。这意味着它的默认值为undefined.

您首先需要使用this.item = new Item().

或者,你可以做

item = {
    barcode: null,
    name: null,
    description: null
}

请注意 can 不能简单地将空对象分配给item,因为您的Item类型需要条形码、名称和描述。


推荐阅读