Не удается прочитать свойство unshift неопределенного - PullRequest
0 голосов
/ 14 октября 2018

Я не знаю, в чем проблема. Я попытался добавить новую книгу в массив своих книг, и я получаю эту ошибку. 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 голосов
/ 14 октября 2018

Для журнала ошибок кажется, что this.books не инициализирован.Можете ли вы инициализировать переменную books в bookservice.ts пустым массивом, например books = []

addBook(book: Book) {
    this.books.unshift(book);
    this.booksChanged.next(this.books);
  }
...