错误 TypeError:无法读取未定义的属性“0”\|角度 4

新手上路,请多包涵

当我尝试打印从 API 获取的 JSON 数据时出现此错误。它确实可以正确打印,但是此错误出现在控制台上,我不确定如何修复它。

HTML

 {{datas[0].dimension}}

TS

 datas: Data[];
this.abcService.getDatas().subscribe(datas => {
  this.datas = datas;
  console.log(datas);
});

从 API (console.log) 获取的 JSON

 (1) [{…}]
0:
  dimension:"bla bla bla"
__proto__:Object
length:1

控制台上的完整错误

ERROR TypeError: Cannot read property '0' of undefined
    at Object.eval [as updateRenderer] (GraphicsComponent.html:11)
    at Object.debugUpdateRenderer [as updateRenderer] (core.es5.js:13113)
    at checkAndUpdateView (core.es5.js:12260)
    at callViewAction (core.es5.js:12620)
    at execComponentViewsAction (core.es5.js:12552)
    at checkAndUpdateView (core.es5.js:12261)
    at callViewAction (core.es5.js:12620)
    at execEmbeddedViewsAction (core.es5.js:12578)
    at checkAndUpdateView (core.es5.js:12256)
    at callViewAction (core.es5.js:12620)

DebugContext_ {view: {…}, nodeIndex: 17, nodeDef: {…}, elDef: {…}, elView: {…}}
component: (...)
componentRenderElement:(...)
context:(...)
elDef:{index: 16, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, …}
elOrCompView:(...)
elView:{def: {…}, parent: {…}, viewContainerParent: null, parentNodeDef: {…}, context: GraphicsComponent, …}
injector:(...)
nodeDef:{index: 17, parent: {…}, renderParent: {…}, bindingIndex: 0, outputIndex: 0, …}
nodeIndex:17
providerTokens:(...)
references:(...)
renderNode:(...)
view:{def: {…}, parent: {…}, viewContainerParent: null, parentNodeDef: {…}, context: GraphicsComponent, …}
__proto__:Object

Obs:HTML 确实打印“bla bla bla”

原文由 Gustavo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 402
2 个回答

它应该是

{{datas && datas[0]?.dimension}}

有关详细信息,请参阅此线程

另一种解决方案是使用空数组初始化属性:

 datas: Data[] = [];

然后就写

{{datas[0]?.dimension}}

原文由 yurzui 发布,翻译遵循 CC BY-SA 3.0 许可协议

添加安全导航运算符以在访问之前检查数据是否存在,因为您正在从异步调用中获取响应

{{datas[0]?.dimension}}

原文由 Sajeetharan 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题