[英]To push a Typescript object to an array of object in angular
I am have a class as follows:我有一个 class 如下:
export class Template {
public Id: Number;
public FileName: string;
}
The following snippet is from a function where I want to first create an object (of type Template
) and push it to the array.以下片段来自 function ,我想首先创建一个 object (类型为Template
)并将其推送到数组。 The code breaks at temp.Id
with error:代码在temp.Id
处中断并出现错误:
ERROR TypeError: Cannot set property 'Id' of undefined.错误类型错误:无法设置未定义的属性“Id”。
The template is initially empty.模板最初是空的。 templates
is an array that contains some file names. templates
是一个包含一些文件名的数组。 Array declared as: templateObjects: Template[] = new Array();
数组声明为: templateObjects: Template[] = new Array();
for (let i = 0; i < this.templates.length; i++) {
var temp: Template;
temp.Id = i;
temp.FileName = this.templates[i].toString();
this.templateObjects.push(temp);
}
u are not newing up Template你没有更新模板
let temp is just declaring variable but new initialize it(allocate memory) then u will be able to assign other properties to it让 temp 只是声明变量但新的初始化它(分配内存)然后你将能够为它分配其他属性
for (let i = 0; i < this.templates.length; i++) {
let temp = new Template() ;
temp.Id = i;
temp.FileName = this.templates[i].toString();
this.templateObjects.push(temp);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.