在 Angular 中,当试图访问一个未定义的属性时,会出现错误信息“Cannot read property 'id' of undefined”。这种错误通常发生在模板中或组件中尝试访问一个不存在的属性时。
以下是解决该问题的几种方法:
{{ object?.id }}
这将在 object 为 undefined 时避免引发错误,并且不会显示任何内容。
if (object && object.id) {
// 这里可以安全地访问 object.id 属性
}
这将确保在 object 或 object.id 为 undefined 时不会引发错误。
const id = object && object.id ? object.id : '默认值';
这样,如果 object 或 object.id 为 undefined,变量 id 将被设置为默认值。
ngOnInit() {
this.getObject().subscribe(object => {
this.object = object;
});
}
这将确保在模板中访问 object.id 时,object 已被正确初始化。
请根据你的具体情况选择适合的解决方法。