通过角度6的TS创建模型类

问题描述 投票:-1回答:2

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

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;
  }
}

现在当我实例化这个模型类时,我得到的错误是this.authors未定义。我正在将我的课程实例化为

let newBook = new BookModel(formValues.id,formValues.AuthorName, formValues.category, formValues.isbn, formValues.description, formValues.pages, formValues.thumbnailUrl, formValues.bookName); 

但它给了我错误:enter image description here

angular typescript
2个回答
3
投票

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

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;
  }
}

1
投票

更改:

public authors:any[];
public categories:any[];

至:

public authors: Array<any>;
public categories: Array<any>;
© www.soinside.com 2019 - 2024. All rights reserved.