【问题标题】:Create and assign a object property dynamically typescript动态创建和分配对象属性打字稿
【发布时间】:2020-08-04 16:41:06
【问题描述】:

我有一个这样声明的接口,

export interface OurHistory {
  ourHistory?: object;
  step1?:object;
  step2?:object;
}

在课堂上,我有

export class HistoryComponent implements OnInit, OnDestroy {
  myHistory:OurHistory;

  let ourHistory = [];
  ourHistory = this.allHistory.fields['ourHistory'];
  this.myHistory.ourHistory = ourHistory[0];
}

我收到一条错误消息,提示无法设置未定义的属性“ourHistory”

【问题讨论】:

  • 因为 myHistory 变量未初始化。默认情况下它是未定义的。
  • 要么从实现接口的类中实例化 myHistory 变量,即 myHistory = new Hisory(),要么使用类似 myHistory: OurHistory = {};

标签: angular typescript angular7


【解决方案1】:

发生这种情况是因为在您的倒数第二行:this.myHistoryundefined。您正在尝试访问undefined 的属性ourHistory,这是编译器不喜欢的。

您需要实例化该属性,就像您问题的 cmets 中提到的那样。

一种方法,可以这样做:

export class HistoryComponent implements OnInit, OnDestroy {
  myHistory: OurHistory;

  let ourHistory = [];
  ourHistory = this.allHistory.fields['ourHistory'];
  this.myHistory = {ourHistory: ourHistory[0]};
}

这样,我们用一个新对象实例化属性myHistory

{
   ourHistory: someValue
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 2020-12-01
    • 2020-12-14
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    相关资源
    最近更新 更多