Angular create object from API

Viewed 924

I am using Angular 8 and I am just trying to take the test JSON api from here: https://jsonplaceholder.typicode.com/users and create an array of User objects out of it like this:

export interface User {
   name: string;
   email: string;
}

I get the data with this:

 this.http.get('https://jsonplaceholder.typicode.com/users').subscribe(data => {
        this.data = data;
        console.log(data);
        });

And I am creating my data variable like this:

data: User[] = [];

It doesn't look like the data array is getting set. Do I need to loop through each object on the response and push it to the data array?

2 Answers

Your API returns more than just the email and name:

{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
        "street": "Kulas Light",
        "suite": "Apt. 556",
        "city": "Gwenborough",
        "zipcode": "92998-3874",
        "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
        }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
        "name": "Romaguera-Crona",
        "catchPhrase": "Multi-layered client-server neural-net",
        "bs": "harness real-time e-markets"
    }
}

So I would probably map your data to each property, so you know exactly what you're extracting from the output:

this.data = data.map((user: any): User => {
    return {
        name: user.name, 
        email: user.email
    }
});

There several ways to do the same:

one of them is : use map to iterate over data and return new object of type User

this.http.get('https://jsonplaceholder.typicode.com/users')
      .subscribe((data :any) => {
        this.users =  data.map((d: any) => {
          let user : User =  {name :d.name , email :d.email };
          return user;
        });
      });

demo

Related