请问您能告诉我如何解决这个问题吗?
浏览器中出现的问题:
core.js:6479 ERROR TypeError: Cannot read properties of undefined (reading 'title')
at BookItemComponent_Template (book-item.component.html:4)
at executeTemplate (core.js:9599)
at refreshView (core.js:9465)
at refreshComponent (core.js:10636)
at refreshChildComponents (core.js:9261)
at refreshView (core.js:9515)
at refreshComponent (core.js:10636)
at refreshChildComponents (core.js:9261)
at refreshView (core.js:9515)
at renderComponentOrTemplate (core.js:9579)
book.service.ts:
import { Injectable } from '@angular/core';
import { Book } from './book.model';
import { HttpClient} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class BookService {
url:string="http://localhost:31451/api/books"
books:Book[];
book:Book;
constructor(private http:HttpClient) { }
getAllbooks (){
this.http.get(this.url).toPromise().then(
res=>{
this.books =res as Book[];
}
)
}
postbook(){
return this.http.post(this.url, this.book);
// {headers: new HttpHeaders({'content-type':'application/json'})}
}
}
书籍模型.ts:
export class Book {
id:number;
title:string;
author:string;
numberOfPages:number;
publishedAt:Date;
}
book-item.component.ts:
import { Component, OnInit } from '@angular/core';
import { BookService } from '../book.service';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-book-item',
templateUrl: './book-item.component.html',
styleUrls: ['./book-item.component.css']
})
export class BookItemComponent implements OnInit {
constructor(public service:BookService) { }
ngOnInit(): void {}
submit() {
this.service.postbook().subscribe(res=>{
this.service.getAllbooks()
},
err=>{
console.log(err)
})
}}
book-item.component.html:
添加数据的表单
<form ngForm="form" (submit)="submit()" >
<div class="form-group">
<label for="title">Title:</label>
<input type="text" [(ngModel)]="service.book.title" name="title" class="form-control">
</div>
<div class="form-group">
<label for="Author">Author:</label>
<input type="text" [(ngModel)]="service.book.author" name="author" class="form-control">
</div>
<div class="form-group">
<label for="numberOfPages">Number Of Pages:</label>
<input type="text" [(ngModel)]="service.book.numberOfPages" name="numberOfPages" class="form-control">
</div>
<div class="form-group">
<label for="publishedAt">published At:</label>
<input type="text" [(ngModel)]="service.book.publishedAt" name="publishedAt" class="form-control">
</div>
<input type="submit" class="btn btn-dark btn-lg" value="save book" >
</form>