AidinTeymouri
AidinTeymouri

Reputation: 15

Angular2 http get first element

I'd like to get just the value of "id" element from this JSON file:

{
"data": {
    "id": 2,
    "first_name": "lucille",
    "last_name": "bluth",
    "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"
}

}

This is my code to fetch the data:

getData() {

    return this.http.get('https://reqres.in/api/users/2')
    .map((respone: Response) => respone.json());
}

How can I get just the 'id' value?

Upvotes: 0

Views: 2444

Answers (4)

Saad Iqbal
Saad Iqbal

Reputation: 108

You can also do this in your component's HTML where you're displaying the data. For example:

<div *ngFor = 'let first of http'>
    {{first.id}}
</div>

Upvotes: 0

Phillip Hartin
Phillip Hartin

Reputation: 889

Assuming you are using RxJs, after you call getData(), you must subscribe to the result, and then parse the data.

i.e.

this.getData().subscribe(result => {

    // handle the response

    return result.data.id;

});

Upvotes: 1

Ajinkya Udgirkar
Ajinkya Udgirkar

Reputation: 223

You can also do something like:

getData() {
    return this.http.get('https://reqres.in/api/users/2')
                    .map((respone: Response) => respone.json().data.id);
}

Will return only the id field from response instead of the entire data object.

Upvotes: 0

Aravind
Aravind

Reputation: 41571

Assuming that you are returning an Observable from your service, You can use variety of RxJs first operator

this.serviceName.getData().first(x => console.log(x.id)) //logs the first id
                          .subscribe(data => console.log(data); // logs the stream of data

Upvotes: 0

Related Questions