0

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?

1
  • 1
    You are getting datetime. You are accessing datatime. What if you use console.log(res.datetime)? Commented May 16, 2019 at 9:37

5 Answers 5

3

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);

    }); 

}
Sign up to request clarification or add additional context in comments.

3 Comments

Can't do that as typescript said "Property datatime does not exist in object"
you should declare res: any
Even better is if you have an interface that represents {name: "peter", datetime: 1557996975991} so you can do like (res: IDataResource). I don't advise using 'any' in TS
1

you r getting value from object use this

console.log(res.datetime)

Comments

0

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)

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.