-1

Sorry if this is obvious but I just cant seem to get my head around it and I cannot think of the right way to phrase my google query (even though I have been trying).

I have the following JSON which is returned from a web API.

{"firstName":"Joe","surname":"bloggs","email":"joe.bloggs@gmail.com"}

I want to access the email from the JSON in my angular app and I getting the data with the followig:

this.auth.getUserDetails(username, password).subscribe(data => {
      console.log(data)
 })

data.email doesnt work, data[2].value doesnt work

How do I specifically reference the email from the data object?

Update

I have just checked the network response to the Web API call and it returns this:

"{\"firstName\":\"Joe\",\"surname\":\"bloggs\",\"email\":\"joe.bloggs@gmail.com\"}"

but just to confirm if I print data to the console I get the first line above.

Update2

Code from getUserDetails:

getUserDetails(username, password){
    let params = new HttpParams({ fromString: 'username=' + username + '&password=' + [password]  });
    return this.httpclient.get(this.myUrl, { params });
  }
Community
  • 1
  • 1
Silentbob
  • 2,805
  • 7
  • 38
  • 70

2 Answers2

0

Based on this answer here - Argument of type 'Response' is not assignable to parameter of type 'string' and @ukn's comment I was able to do the following:

let userDetails = JSON.parse(data.toString());
console.log(userDetails.email);
Silentbob
  • 2,805
  • 7
  • 38
  • 70
0

It would be better if you created an interface for your user and it would simplify this problem and other problems you would have in future.

export interface user {
firstname: string,
surname: string,
email: string
}

Then using it to get the data like:

return this.httpclient.get<user>(this.myUrl, { params });

Then you can use the data like you want after the response.

this.auth.getUserDetails(username, password).subscribe(data => {
      console.log(data.email)
 })
Kiril1512
  • 3,231
  • 3
  • 16
  • 41