angular - Angular 2+ / Typescript 无法读取未定义的属性
问题描述
我正在使用 Angular 7,并且从服务中获取这些数据:
{name: "peter", datetime: 1557996975991}
然后我有这个获取数据的方法:
myMethod() {
this.myService.getdata().subscribe((res) => {
console.log(res); // returns: {name: "peter", datetime: 1557996975991}
console.log(res[0].datatime); // Gives Error: Cannot read property 'datetime' of undefined
});
}
当我尝试获取数据时间值时,我得到:
给出错误:无法读取未定义的属性“日期时间”
我怎样才能解决这个问题?
解决方案
res 变量是对象而不是数组。
您需要更改为console.log(res.datatime);
改成
myMethod() {
this.myService.getdata().subscribe((res: any) => {
console.log(res); // returns: {name: "peter", datetime: 1557996975991}
console.log(res.datatime);
});
}
推荐阅读
- kubernetes - Kubernetes如何限制节点上相同的pitch数?
- python - tensorflow.data_flow_ops 中的 queue.dequeue_up_to() 方法是做什么用的?
- material-ui - 使用 material-ui 样式化 react-select v2 - 替换输入组件
- php - 如何测试文件是否是任何类型的代码、字符串或文本文件?(php)
- python - 将String数值拆分成新列-Pandas Dataframe
- r - 根据条件组合数据框列?
- javascript - Highcharts - 在图例中禁用时,行标签仍然出现
- python - 使用 Jupyter Notebook 从 Kaggle 中提取泰坦尼克号训练数据的问题
- sql - SQL Distinct 具有多个条件
- python - NetworkX:折线图及其补集