无法读取未定义的属性“ unshift”

时间:2018-10-14 07:00:13

标签: arrays angular typescript undefined

我不知道我试图将一本新书推到我的书本数组中的问题在哪里,并且出现此错误。enter image description here

这是 book-edit.component.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);
  }

这是我从 booksService.ts

调用的函数
addBook(book: Book) {
    this.books.unshift(book);
    this.booksChanged.next(this.books);
  }

1 个答案:

答案 0 :(得分:0)

对于错误日志,似乎this.books未初始化。您可以将bookservice.ts中的books变量初始化为像books = []

这样的空数组吗?
addBook(book: Book) {
    this.books.unshift(book);
    this.booksChanged.next(this.books);
  }