在Angular 6中通过TS创建模型类

Nit*_*ana 0 typescript angular

我正在尝试在我的角度应用程序中创建一个模型类,如下所示:

export class BookModel {
  public _id:any;
  public authors:any[];
  public categories:any[];
  public isbn:any;
  public longDescription:any;
  public pageCount:any;
  public thumbnailUrl:any;
  public title:any;

  constructor(id,author, category, isbn, longDescription, pageCount, thumbnailUrl, title) {
    this._id = id;
    this.authors.push(author);
    this.categories.push(category);
    this.isbn = isbn;
    this.longDescription = longDescription;
    this.pageCount = pageCount;
    this.thumbnailUrl = thumbnailUrl;
    this.title = title;
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,当我实例化这个模型类时,我收到错误,指出 this.authors 未定义。我将我的类实例化为

let newBook = new BookModel(formValues.id,formValues.AuthorName, formValues.category, formValues.isbn, formValues.description, formValues.pages, formValues.thumbnailUrl, formValues.bookName); 
Run Code Online (Sandbox Code Playgroud)

但它给了我错误: 在此输入图像描述

Sur*_*yan 5

您需要首先初始化数组然后使用它们。初始化时会在内存中为它们分配一个空间。

export class BookModel {
  public _id: any;
  public authors: any[] = []; // <- Initializing
  public categories: any[] = []; // <- Initializing
  public isbn: any;
  public longDescription: any;
  public pageCount: any;
  public thumbnailUrl: any;
  public title: any;

  constructor(id, author, category, isbn, longDescription, pageCount, thumbnailUrl, title) {
    this._id = id;
    this.authors.push(author);
    this.categories.push(category);
    this.isbn = isbn;
    this.longDescription = longDescription;
    this.pageCount = pageCount;
    this.thumbnailUrl = thumbnailUrl;
    this.title = title;
  }
}
Run Code Online (Sandbox Code Playgroud)