【发布时间】:2019-07-21 19:43:19
【问题描述】:
我正在尝试使用表单中的 HttpClient 和 [(ngModel)] 指令从 Angular 应用程序向 nestJS 服务器发出发布请求。当我提交表单时,我收到以下错误:
AppComponent.html:34 ERROR TypeError: Cannot read property 'id' of undefined
at AppComponent.addBook (app.component.ts:21)
at Object.eval [as handleEvent] (AppComponent.html:34)
at handleEvent (core.js:38098)
at callWithDebugContext (core.js:39716)
at Object.debugHandleEvent [as handleEvent] (core.js:39352)
at dispatchEvent (core.js:25818)
at core.js:37030
at HTMLButtonElement.<anonymous> (platform-browser.js:1789)
at ZoneDelegate.invokeTask (zone-evergreen.js:391)
at Object.onInvokeTask (core.js:34182)
这里是component.html 文件,它使用了未定义变量的 'id' 属性,它应该是真正的书籍对象:
//app.component.html
<form class="" action="addBook()" method="post">
<div class="form-group">
<label for="id">Book ID:</label>
<input id="id" name="bookID" type="text" [(ngModel)]="id" class="form-control">
<label for="title">Book Title:</label>
<input id="title" name="bookTitle" type="text" [(ngModel)]="title" class="form-control">
<label for="description">Book Description:</label>
<input id="description" name="bookDescription" type="text" [(ngModel)]="description" class="form-control">
<label for="author">Book Author:</label>
<input id="author" name="bookAuthor" type="text" [(ngModel)]="author" class="form-control">
<button type="submit" name="button" (click)="addBook()">add</button>
</div>
</form>
[(ngModel)] 指令中使用的所有属性都属于一个书籍对象,在app.component.ts 文件中定义:
//app.component.ts
import { Component } from '@angular/core';
import { ApiService } from './api.service';
import { Book } from './book';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
book: Book;
constructor(private apiService: ApiService){}
library = {};
ngOnInit(){
}
getBooks() {
this.apiService.getBooks().subscribe(data => this.library = data);
};
addBook(){
let book = {
id: this.book.id,
title: this.book.title,
description: this.book.description,
author: this.book.author
}
this.apiService.addBook(book).subscribe(
success => alert("Done"),
error => alert(error)
)
}
clearview() {
this.library = {}
};
}
这本书对象的类型是 Book,它是一个如下所示的类:
export class Book{
id: Number;
title: string;
description: string;
author: string;
}
很抱歉,如果我把它弄得比需要的长,我想提供完整的上下文,因为我已经尝试了许多不同的方法来修复这个错误。
【问题讨论】:
-
嗯,书永远不会初始化/设置为一个值,如果书是
undefined,你怎么能id: this.book.id?
标签: node.js angular typescript