【Angular2】Uncaught (in promise): TypeError: Cannot read property 'id'

来源:互联网 发布:通信网络优化值得做吗 编辑:程序博客网 时间:2024/06/05 05:45

背景

需要显示用户信息,用到了插值表达式和双向绑定
开始数据显示正常,但是浏览器一直报错,不知为何

因为可以正常运行,所以就继续做
但是用到后台返回值来切换编辑状态的时候,什么都不显示
所以就得解决了这个问题

问题

这里写图片描述

ERROR Error: Uncaught (in promise): TypeError: Cannot read property ‘id’ of undefined

TypeError: Cannot read property ‘id’ of undefined

解决

1.使用箭头函数

 getStudents():void{    this.studentService.getStudents().then(students=>this.students=students);  }

2.在插值表达式中加入问号

{{student?.name}} //not {{student.name}}

 

说明:

因为在我们加载对象的时候,用的是异步模式,即使promise立刻被处理返回,但是浏览器在开始加载对象的时候,这个对象还是没有定义,所以也就读不到属性

参考:

https://stackoverflow.com/questions/38078741/angularjs-2-exception-error-uncaught-in-promise-typeerror-cannot-set-prope

阅读全文
0 0
原创粉丝点击