![](/img/trans.png)
[英]Typescript: Uncaught typeError, Cannot read property "push" of undefined
[英]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.