Angular运行报错TypeError: 无法读取undefined的'title'属性怎么解决
问题原因
你在BookService中仅声明了book: Book类型的属性,未对其进行初始化,该属性默认值为undefined。模板代码中直接通过[(ngModel)]="service.book.title"读取undefined的title属性,触发了此次类型报错。
解决步骤
步骤1:完善Book类的初始化逻辑
修改book.model.ts,给Book类添加构造函数,初始化所有属性的默认值:
export class Book { id:number; title:string; author:string; numberOfPages:number; publishedAt:Date; constructor() { this.id = 0; this.title = ''; this.author = ''; this.numberOfPages = 0; this.publishedAt = new Date(); } }
步骤2:在BookService中初始化book实例
修改book.service.ts的构造函数,初始化book属性:
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) { // 新增初始化代码 this.book = new Book(); } getAllbooks (){ this.http.get(this.url).toPromise().then( res=>{ this.books =res as Book[]; } ) } postbook(){ return this.http.post(this.url, this.book); } }
可选优化:提交成功后重置表单
如果需要新增成功后清空表单,可修改book-item.component.ts的submit方法:
submit() { this.service.postbook().subscribe(res=>{ this.service.getAllbooks(); // 新增重置book实例代码,清空表单 this.service.book = new Book(); }, err=>{ console.log(err) }) }
临时避错方案(不推荐):如果仅需要先消除报错,可在模板绑定中使用可选链,如
[(ngModel)]="service.book?.title",但可选链仅支持读取属性,双向绑定的赋值逻辑会失效,因此优先选择初始化实例的方案。
内容的提问来源于stack exchange,提问作者abdulraheem alarpi
相关产品推荐
相关产品推荐

