0

I am looking to fetch all the 'firstName's only from the below JSON data in Angular HttpGet method.

[
    {
    "id": "65664546",
    "name": "Employee 1",
    "contacts":
        {
            "id": "56546564",
            "firstName": "James",
            "lastName": "Carter",
            "email": "[email protected]"
        }
    },
    {
    "id": "65664547",
    "name": "Employee 2",
    "contacts":
        {
            "id": "56546565",
            "firstName": "Steve",
            "lastName": "Smith",
            "email": "[email protected]"
        }
    },
    {
    "id": "65664548",
    "name": "Employee 3",
    "contacts":
        {
            "id": "56546566",
            "firstName": "Anna",
            "lastName": "Marcus",
            "email": "[email protected]"
        }
    }
    ]

Please can you advise, what would the Httpget method and subscribe method for it look like.

0

2 Answers 2

1

You may do so using the following code:

constructor(private http: HttpClient) { }

ngOnInit() {

   this.http.get("./assets/mydata.json")   // path to your json file
       .pipe(
          map(emp => emp.map(e => e.contacts.firstName))
       ) // from the json array "map" the first name
       .subscribe(res => console.log(res));
}
Sign up to request clarification or add additional context in comments.

Comments

0

First question that comes to mind is – do you control the backend that provides that JSON? If so, you could create a separate action method (maybe a Microsoft term?) that provides a list of strings containing firstName only. I won't go into examples since I don't know which backend tech you use, if at all.

On the other hand, if you don't control the backend, you could do several things on your side of things.

First of all, you could subscribe to the HTTP stream and map the result:

this.http.get("whatever").subscribe(res => res.map(x => x.firstName));

This is, of course, just an example. I don't know how you structured your app and where the subscribing happens. Could be on services, could be on components, or via async pipe.

Better yet, you could take Nicholas K's advice and go reactive with pipe(map(...)). I won't repeat his answer for several obvious reasons.

I can't think of another alternative.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.