在TypeScript中创建Model类的变量

时间:2019-09-24 16:08:19

标签: angular typescript

我有模型EmailModel类模型:

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

然后我创建了类emailModel的变量EmailModel。 这是我的变量:emailModel =< EmailModel>{};

使用this.emailModel.product时会出现未定义的错误,但是使用this.emailModel.name或其他属性进行翻转时效果很好。

3 个答案:

答案 0 :(得分:1)

您需要像这样将数组初始化为空数组,以便像对象的普通属性一样使用

public product: ProductModelOrder[] = [];

答案 1 :(得分:1)

product属性是“ ProductModelOrder”的数组,还应该初始化

答案 2 :(得分:1)

一件事是您的类定义,另一件事是实例化您的对象。 您的类定义看起来不错。

现在让我们尝试实例化:

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".

请注意,我已将属性EmailModel.product重命名为EmailModel.product s 因为它可以包含许多产品。