我正在尝试在我的角度应用程序中创建一个模型类,如下所示:
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);
答案 0 :(得分: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 :(得分:1)
change:
public authors:any[];
public categories:any[];
to:
public authors: Array<any>;
public categories: Array<any>;