Reputation:
I am using Angular 7 and I am getting this data from a service:
{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
How can I fix this?
Upvotes: 0
Views: 422
Reputation: 173
Yes as @FailedUnitTest has said you the best way is declare an interface and in that way you can access to this values. Avoid use 'any' always because when the code gets harder and bigger maybe you could get into some troubles.
Upvotes: 0
Reputation: 18975
The res variable is object not array.
You need change to 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);
});
}
Upvotes: 3
Reputation: 422
you r getting value from object use this
console.log(res.datetime)
Upvotes: 1
Reputation: 440
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}
.
As Hein pointed, you should access the datatime
property with console.log(res.datatime)
Upvotes: 0