Arrays 无法读取属性';取消移位';未定义的
我不知道问题出在哪里,我试图将一本新书推送到我的books数组,但我得到了这个错误 这是book edit.component.ts的Arrays 无法读取属性';取消移位';未定义的,arrays,angular,typescript,undefined,Arrays,Angular,Typescript,Undefined,我不知道问题出在哪里,我试图将一本新书推送到我的books数组,但我得到了这个错误 这是book edit.component.ts的 ngOnInit() { this.authorsService.authorsChanged.subscribe( (authors: Author[]) => { this.authors = authors; } ); this.authorsService.getAuthors();
ngOnInit() {
this.authorsService.authorsChanged.subscribe(
(authors: Author[]) => {
this.authors = authors;
}
);
this.authorsService.getAuthors();
this.bookForm = new FormGroup({
'id': new FormControl(Math.floor(Math.random() * 10000000000)),
'title': new FormControl('new book'),
'author': new FormControl(null),
'description': new FormControl('description'),
'publishYear': new FormControl('1991'),
'image': new FormControl('https://www.reduceimages.com/img/image-after.jpg')
});
}
onSubmit() {
const book = {
id: this.bookForm.value.id,
title: this.bookForm.value.title,
author: this.bookForm.value.author,
description: this.bookForm.value.description,
publishYear: this.bookForm.value.publishYear,
image: this.bookForm.value.image
};
this.booksService.addBook(book);
console.log(book);
}
addBook(book: Book) {
this.books.unshift(book);
this.booksChanged.next(this.books);
}
这是我从bookservice.ts调用的函数
ngOnInit() {
this.authorsService.authorsChanged.subscribe(
(authors: Author[]) => {
this.authors = authors;
}
);
this.authorsService.getAuthors();
this.bookForm = new FormGroup({
'id': new FormControl(Math.floor(Math.random() * 10000000000)),
'title': new FormControl('new book'),
'author': new FormControl(null),
'description': new FormControl('description'),
'publishYear': new FormControl('1991'),
'image': new FormControl('https://www.reduceimages.com/img/image-after.jpg')
});
}
onSubmit() {
const book = {
id: this.bookForm.value.id,
title: this.bookForm.value.title,
author: this.bookForm.value.author,
description: this.bookForm.value.description,
publishYear: this.bookForm.value.publishYear,
image: this.bookForm.value.image
};
this.booksService.addBook(book);
console.log(book);
}
addBook(book: Book) {
this.books.unshift(book);
this.booksChanged.next(this.books);
}
对于错误日志,似乎未初始化
this.books
。能否将bookservice.ts中的books
变量初始化为空数组,如books=[]
addBook(book: Book) {
this.books.unshift(book);
this.booksChanged.next(this.books);
}
全套服务代码是多少?服务中的
图书
似乎从未初始化。您的图书服务中的图书
似乎未初始化。这样做:books=[]代码>在您的BookService中。