【问题标题】:To push a Typescript object to an array of object in angular将 Typescript 对象推送到角度对象数组
【发布时间】:2020-10-28 03:50:04
【问题描述】:

我有一门课如下:

export class Template {
  public Id: Number;
  public FileName: string;
}

以下 sn-p 来自我想首先创建一个对象(Template 类型)并将其推送到数组的函数。代码在temp.Id 处出现错误:

错误类型错误:无法设置未定义的属性“Id”。

模板最初是空的。 templates 是一个包含一些文件名的数组。数组声明为: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);
}

【问题讨论】:

    标签: javascript arrays angular typescript javascript-objects


    【解决方案1】:

    你没有更新模板

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

    【讨论】:

    • 嘿哈南,非常感谢!你刚刚为我解决了一些我苦苦挣扎了好几个小时的事情。
    猜你喜欢
    • 1970-01-01
    • 2018-11-10
    • 2019-07-19
    • 2022-01-18
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多