繁体   English   中英

错误TypeError:无法读取TypeScript中未定义的属性“ push”

[英]ERROR TypeError: Cannot read property 'push' of undefined in TypeScript

我有TypeScript的基本问题。 我有一个错误:

ERROR TypeError: Cannot read property 'push' of undefined

我有模型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: Array<ProductModelOrder>=[];

    constructor(name: String, lastname: String, address: String, company: String, zipcode: number, city: String, phonenumber: number, email: String,product: Array<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;
    }
}

我的product数组如下所示:

export class ProductModelOrder {
    public name: String;
    public number: number;
    public pricePerProduct:number;
    public price:number;
}

这是我的productOrder =< ProductModelOrder>{}; emailModel = <EmailModel>{}; 而且我想要productOrder到emailModel像这样:

for (let prod of this.productCarts){
      this.productOrder.name = prod.product_name;
      this.productOrder.number = prod.numberOfProduct;
      this.productOrder.pricePerProduct = prod.product_price;  
      this.productOrder.price = this.priceForAllProducts; 
      this.emailModel.product.push(this.productOrder);
    }

而且我有错误。

正如您提到的,您的emailModel = <EmailModel>{}; 所以product属性是undefined那么你就是this.emailModel.product.push(this.productOrder); 导致错误的

因此,您需要做的是emailModel = new EmailModel(...params here);

你也可以做到这一点

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: Array<ProductModelOrder>=[];

    constructor(params: EmailModel) {
       Object.assign(this, params);
    }
}

然后

emailModel = new EmailModel({...params here});

简单的例子

export class Person {
   name: string;
   phones: Array<string>;
   age?:number; //optional

   constrcutor(params: Person) {
     Object.assign(this, params);
   }
}

const p = new Person({name: 'Reza', phones: ['6583992']})

暂无
暂无

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

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