SIn san sun
SIn san sun

Reputation: 633

Create variable of Model class in TypeScript

I have model EmailModel class model :

    export class EmailModel {

    public name: String;
    public lastname: String;
    public address: String;
    public company: String;
    public zipcode: number;
    public city: String;
    public phonenumber: number;
    public email: String;
    public product: ProductModelOrder[] = [];



    constructor(name: String, lastname: String, address: String, company: String, zipcode: number, city: String, phonenumber: number, email: String,product: ProductModelOrder[]) {
        this.name = name;
        this.lastname = lastname;
        this.address = address;
        this.company = company;
        this.zipcode = zipcode;
        this.city = city;
        this.phonenumber = phonenumber;
        this.email = email;
        this.product = product;
    }
}

And I created the variable emailModel of my class EmailModel. This is my var: emailModel =< EmailModel>{};

I get the undefined error when I using the this.emailModel.product, but when I using the this.emailModel.name or other properties everting is well.

Upvotes: 0

Views: 2080

Answers (3)

Gabriel Marcondes
Gabriel Marcondes

Reputation: 1010

One thing is your class definition, other thing is instantiating your object. Your class definition looks alright.

Now lets try to instantiate:

let products: ProductModelOrder[] = []; //Creates an instance for the array of products
let product: ProductModelOrder = new ProductModelOrder(...); //Creates an instance for a product
product.someproperty = "somevalue"; //Sets value to property
products.push(product); //Adds the product to the list

let emailModel = new EmailModel(..., products); //Instantiates the main object, passing the instantiated array

console.log(emailModel.products[0].someproperty);//Logs the value of the property "someproperty", in this example it should print "somevalue".

Please note that I have renamed the property EmailModel.product to EmailModel.products because it can contain many products.

Upvotes: 1

Zouhair Ettouhami
Zouhair Ettouhami

Reputation: 226

The product attribute is an array of "ProductModelOrder" and should also be initialized

Upvotes: 1

Pardeep Jain
Pardeep Jain

Reputation: 86800

you need to initilize array to be as empty array like this in order to use like normal property of object -

public product: ProductModelOrder[] = [];

Upvotes: 1

Related Questions