错误TypeError:无法读取undefined |的属性“0” Angular 4

时间:2017-09-21 17:41:43

标签: javascript json angular typescript

当我尝试从API获取的JSON中打印数据时,我收到此错误。它确实打印正确但是这个错误出现在控制台上,我不知道如何解决它。

HTML

{{datas[0].dimension}}

TS

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

JSON来自API(console.log)

(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”

3 个答案:

答案 0 :(得分:9)

应该是

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

有关详细信息,请参阅此主题

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

datas: Data[] = [];

然后写下

{{datas[0]?.dimension}}

答案 1 :(得分:2)

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

{{datas[0]?.dimension}}

答案 2 :(得分:0)

您收到此错误是因为您的视图中的绑定数据为空格而角度编译html,因为Observable.subscribe将在收到服务响应时为您提供数据。

因此,您可以初始化它以避免错误或未定义的测试,然后使用它。

{{datas[0]?.dimension}}  //will work file

希望有所帮助