Angular TypeError:对象(_co.book)为空?
这是控制台显示的内容:
ERROR TypeError: "_co.book is null" View_SingleBookComponent_0 SingleBookComponent.html:3 Angular 24 RxJS 5 Angular 11 SingleBookComponent.html:3:4 ERROR CONTEXT {…} ​ elDef: Object { nodeIndex: 2, bindingIndex: 0, outputIndex: 0, … } ​ elView: Object { def: {…}, parent: {…}, state: 1164, … } ​ nodeDef: Object { nodeIndex: 3, bindingIndex: 0, outputIndex: 0, … } ​ nodeIndex: 3 ​ view: Object { def: {…}, parent: {…}, state: 1164, … }...
该页面必须显示书籍的信息(作者姓名和书名)
这是 single-book.component.ts 代码:
export class SingleBookComponent implements OnInit {
book: Book;
constructor(private route: ActivatedRoute, private booksService: BooksService,
private router: Router) {}
ngOnInit() {
this.book = new Book('', '');
const id = this.route.snapshot.params[' id'];
this.booksService.getSingleBook(+id).then(
(book: Book) => {
this.book = book;
}
);
}
onBack() {
this.router.navigate(['/books']);
}
}
//This is the book-form.component.ts code
export class BookFormComponent implements OnInit {
bookForm: FormGroup;
fileIsUploding = false;
fileURL: string;
fileUploaded = false;
constructor(private formBuilder: FormBuilder,
private booksService: BooksService,
private router: Router) { }
ngOnInit() {
this.initForm();
}
initForm() {
this.bookForm = this.formBuilder.group({
title: ['', Validators.required],
author: ['', Validators.required]
});
}
onSaveBook() {
const title = this.bookForm.get('title').value;
const author = this.bookForm.get('author').value;
const newBook = new Book (title, author);
if (this.fileURL && this.fileURL !== '' ) {
newBook.photo = this.fileURL;
}
this.booksService.createNewBook(newBook);
this.router.navigate(['/book']);
}
在使用
book
的 html 中添加 elvis 运算符 -
?
,如下所示:
*ngIf="book?.photo"
或者您也可以将
*ngIf="book"
添加到包装图书数据的
div
元素中
在组件呈现时,
book
尚未设置。只需将
this.book = new Book('', '');
移至构造函数或直接移至构造函数上方的变量声明即可。
或者,将组件的代码包装在
*ngIf
中,例如:
<ng-container *ngIf="book">
<div ...></div>
</ng-container>
const id = this.route.snapshot.params[' id'];
id 元素前有一个空格,导致 id 为空。 应为:
const id = this.route.snapshot.params['id'];
或
const id = this.route.snapshot.params.id;