angular - 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);
}
);
}
解决方案
目前,虽然您的item
字段已声明,但尚未初始化。这意味着它的默认值为undefined
.
您首先需要使用this.item = new Item()
.
或者,你可以做
item = {
barcode: null,
name: null,
description: null
}
请注意 can 不能简单地将空对象分配给item
,因为您的Item
类型需要条形码、名称和描述。
推荐阅读
- python - 来自多列和字典条件的新数据框
- java - 如何在`onCreate()`中只调用一次方法并在更改活动时继续运行它
- python - 为选择列/分层列创建顶部列层
- javascript - How to assign the value to the element of an array of the object and return the updated object typscript
- html - HTML将画布放在按钮顶部
- viewcontroller - 类型“ViewController”不符合协议“CBCentralManagerDelegate”
- python-3.x - 来自 MDToolbar 的空白空白重叠 KivyMD ImageList
- amazon-web-services - 创建需要多个工人的机械土耳其人 HIT
- go - 找不到包“。” 在 .../vendor/github.com/godror/godror
- javascript - 在模板中序列化 Django 用户:Group 类型的对象不是 JSON 可序列化的