user11447349
user11447349

Reputation:

Angular 2+ / Typescript Cannot read property of undefined

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

Answers (5)

Darwin Gonzalez
Darwin Gonzalez

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

sandrooco
sandrooco

Reputation: 8716

console.log(res.datetime); - note the e in datetime.

Upvotes: 0

Hien Nguyen
Hien Nguyen

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

Syed Kashif
Syed Kashif

Reputation: 422

you r getting value from object use this

console.log(res.datetime)

Upvotes: 1

Manish Shrestha
Manish Shrestha

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

Related Questions