Nitesh Rana
Nitesh Rana

Reputation: 512

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. 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: enter image description here

Upvotes: 0

Views: 12131

Answers (2)

Ayoub k
Ayoub k

Reputation: 8868

change:

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

to:

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

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68665

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

Upvotes: 5

Related Questions