开发者问题收集

错误 TypeError:无法读取未定义的属性‘0’| Angular 4

2017-09-21
30215

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

HTML

{{datas[0].dimension}}

TS

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

从 API 获取的 JSON(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

注意:HTML 确实打印“bla bla bla”

3个回答

应该是

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

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

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

datas: Data[] = [];

然后只需写入

{{datas[0]?.dimension}}
yurzui
2017-09-21

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

{{datas[0]?.dimension}}
Sajeetharan
2017-09-21

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

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

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

希望有帮助

Aniruddha Das
2017-09-21