2

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?

3
  • It works fine for me: stackblitz.com/edit/angular-tdst6h Commented Oct 24, 2019 at 4:46
  • @AndreiRosu that only stores the entire data response, I only want to store an array of User objects in the data variable. Commented Oct 24, 2019 at 4:49
  • 1
    Then you need to map your data after you received it. learnrxjs.io/operators/transformation/map.html Commented Oct 24, 2019 at 4:54

2 Answers 2

2

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

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

Comments

2

Your API returns more than just the email and name:

{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "[email protected]",
    "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
    }
});

1 Comment

when trying to map the data from the API, I get error that property map does not exist on type Object

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.