我有一个这样声明的接口,
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”
答案 0 :(得分:0)
之所以会这样,是因为在倒数第二行上:this.myHistory
是undefined
。您正在尝试访问编译器不喜欢的ourHistory
的属性undefined
。
您需要实例化属性,如问题注释中所述。
一种实现方式,可以这样做:
export class HistoryComponent implements OnInit, OnDestroy {
myHistory: OurHistory;
let ourHistory = [];
ourHistory = this.allHistory.fields['ourHistory'];
this.myHistory = {ourHistory: ourHistory[0]};
}
这样,我们用新对象实例化属性myHistory
:
{
ourHistory: someValue
}