当出现"Cannot Read Property 'example' of Undefined"的报错时,通常是因为未定义或未赋值所引用的属性或变量。 解决方法是在使用这个属性或变量之前,保证它是已被定义或已经赋值。例如,可以在声明时给属性或变量赋默认值,或者在它们被使用前进行判断和赋值。 示例代码如下:
export class ExampleComponent implements OnInit { example: string;
ngOnInit(): void { if (!this.example) { this.example = 'default value'; } console.log(this.example); } }