0

Using Angular 5 with the HttpClient, I have seen examples of something like:

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>('https://jsonplaceholder.typicode.com/users');
  }

I am trying to understand the many ways of achieving mapping the JSON array of users to my User array.

Does Angular know how to map the data as above, or do I have to perform the .map function to build the User array myself?

2
  • 2
    If you are using the generic method you don't need to map. Just subscribe and get your parsed data. Commented Apr 12, 2018 at 15:10
  • Thank you! yes makes sense. Commented Apr 13, 2018 at 7:41

1 Answer 1

1

you can do simply

getUsers() {
  return this.http.get('https://jsonplaceholder.typicode.com/users');
}

if your response is something like this:

[
  {
    "id": 1,
    "name": "example1",
  },
  {
    "id": 2,
    "name": "example2",
  }
]

then you can do this:

this.service.getUsers().subscribe(
  result => {
    this.arrayUsers = result;
  }
)

else if you have it deeper in your JSON:

{
  "success":[
    {
       "id": 1,
       "name": "example1",
    },
    {
       "id": 2,
       "name": "example2",
    }
 ]

}

then you should do in this way:

this.service.getUsers().subscribe(
  result => {
    this.arrayUsers = result['success']; 
  }
)
Sign up to request clarification or add additional context in comments.

1 Comment

Hey thanks for confirming that. I realised afterwards that I was trying to do something like automapper in the .NET world i.e. if the JSON result had more fields than I wanted, I just thought the this.http.get<User[]> would map only the data from the JSON to my User array. I have since seen some deserialisation examples which seem to do that - I am just trying to find the most efficient way. Many thanks for responding!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.