简体   繁体   English

在 TypeScript 中创建 Model class 的变量

[英]Create variable of Model class in TypeScript

I have model EmailModel class model:我有 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 .我创建了我的 class EmailModel emailModel This is my var: emailModel =< EmailModel>{};这是我的变量: 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.当我使用this.emailModel.product时出现未定义的错误,但是当我使用this.emailModel.name或其他属性时,一切都很好。

you need to initilize array to be as empty array like this in order to use like normal property of object -您需要将数组初始化为像这样的空数组,以便使用 object 的正常属性 -

public product: ProductModelOrder[] = [];

The product attribute is an array of "ProductModelOrder" and should also be initialized产品属性是“ProductModelOrder”的数组,也应该被初始化

One thing is your class definition, other thing is instantiating your object.一件事是您的 class 定义,另一件事是实例化您的 object。 Your class definition looks alright.您的 class 定义看起来不错。

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.product s because it can contain many products.请注意,我已将属性 EmailModel.product 重命名为 EmailModel.product 因为它可以包含许多产品。

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

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