简体   繁体   English

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

[英]Creating model class through TS in angular 6

I am trying to create a model class in my angular app which goes like this: 我试图在我的角度应用程序中创建一个模型类,如下所示:

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

Now when i am instantiating this model class I am getting error that this.authors is undefined. 现在,当我实例化此模型类时,我收到错误消息this.authors未定义。 I am instantiating my class as 我正在将我的课程实例化为

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

But it gives me error: 但这给了我错误: 在此处输入图片说明

You need first to initialize your arrays and then use them. 您首先需要初始化数组,然后使用它们。 Initializing will allocate a space for them in the memory. 初始化将在内存中为其分配空间。

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

change: 更改:

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

to: 至:

public authors: Array<any>;
public categories: Array<any>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM