简体   繁体   English

如何处理角度5中的未定义对象属性

[英]How to handle undefined object property in angular 5

I tried to fix the undefined error by setting the object property value to an empty string but its still giving the error as mentioned below: 我试图通过将对象属性值设置为空字符串来修复未定义的错误,但仍会给出如下所述的错误:

ERROR TypeError: Cannot read property 'notes' of undefined 错误TypeError:无法读取未定义的属性“注释”

TS TS

let notes;
if (typeof manufacturer_field.manufacturer_guidelines[0].notes == undefined){
  notes = '';
} else {
  notes = manufacturer_field.manufacturer_guidelines[0].notes;
}

HTML HTML

<p *ngIf="field.notes?.length">{{field.notes}}</p>

I referred this answer but that didn't work: How to handle 'undefined' in javascript 我提到了这个答案,但是没有用: 如何处理javascript中的“未定义”

If notes array element 0 is undefined, then this will throw an error: 如果注释数组元素0未定义,则将引发错误:

if (typeof manufacturer_field.manufacturer_guidelines[0].notes == undefined){

because you are checking if the property is undefined, when what is actually undefined is the .manufacturer_guidelines[0] item. 因为您正在检查属性是否未定义,所以.manufacturer_guidelines [0]项实际上是未定义的时间。

instead, you can do: 相反,您可以执行以下操作:

if (!manufacturer_field.manufacturer_guidelines[0]){
     manufacturer_field.manufacturer_guidelines[0] = (assign it whatever value belong to this sort of item, and then once you know it is valid, then add notes)
}

Also, you are assigning the string to "notes" variable, not the actual array item. 另外,您正在将字符串分配给“ notes”变量,而不是实际的数组项。

So lets say i had a cars array: 所以可以说我有一个汽车阵列:

if (!cars[0]) {
   cars[0] = <Car>{};
   cars[0].color = "blue";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM