[英]Angular 2+ / Typescript Cannot read property of undefined
I am using Angular 7 and I am getting this data from a service: 我正在使用Angular 7,并且正在从服务获取此数据:
{name: "peter", datetime: 1557996975991}
Then I have this method that gets the data: 然后我有这种方法来获取数据:
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
});
}
When I try to get the datatime value I'm getting: 当我尝试获取数据时间值时,我得到:
Gives Error: Cannot read property 'datetime' of undefined 给出错误:无法读取未定义的属性“ datetime”
How can I fix this? 我怎样才能解决这个问题?
The res variable is object not array. res变量是对象而不是数组。
You need change to console.log(res.datatime);
您需要更改console.log(res.datatime);
Change to 改成
myMethod() {
this.myService.getdata().subscribe((res: any) => {
console.log(res); // returns: {name: "peter", datetime: 1557996975991}
console.log(res.datatime);
});
}
您从对象中获得价值使用此
console.log(res.datetime)
You are confusing your objects and arrays. 您在混淆对象和数组。
When you do console.log(res[0].datatime)
, you're understanding the response as an array when you can clearly see it is an object here: {name: "peter", datetime: 1557996975991}
. 当您执行console.log(res[0].datatime)
,您将在这里清楚地看到它是一个对象时,将响应理解为一个数组: {name: "peter", datetime: 1557996975991}
。
As Hein pointed, you should access the datatime
property with console.log(res.datatime)
由于海因指出,你应该访问datatime
财产console.log(res.datatime)
console.log(res.datetime);
- note the e
in datetime
. -注意datetime
的e
。
Yes as @FailedUnitTest has said you the best way is declare an interface and in that way you can access to this values. 是的,就像@FailedUnitTest所说的那样,最好的方法是声明一个接口,这样您就可以访问此值。 Avoid use 'any' always because when the code gets harder and bigger maybe you could get into some troubles. 始终避免使用“ any”,因为当代码变得越来越困难时,您可能会遇到一些麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.