Issue
I´ve a REST API that returns json data in the following structure - the content itself is inside a "data" node, cause sometimes there will be additional meta information in the request (e.g. for pagination).
{
"data": [
{
"id": 1,
"title": "List 1"
},
{
"id": 2,
"title": "List 2"
},
]
}
I fetch the data with the Angular http Client as follows:
getLists (): Observable<List[]> {
return this._httpClient.get<List[]>('http://localhost/api/v1/lists').pipe(
tap((response) => {
this._lists.next(response)
}),
)
}
The issue - as you may already - is, that the response is not an array of elements of type "List", cause the elements are inside the "data" node. Accessing the content inside the data node on the response object will also not work, cause of the set generic / expected return type.
Is there a way to keep using the generic on the get() method and access the content inside the "data" array, so that it ends up in an array of List objects?
Solution
The closest thing possible (assuming you want to use the generic) is to define a Response
type, like this:
interface Response {
data: List[]
}
and then you can change the HTTP client to use Response instead, and add a map
stage, so you can get the data:
getLists (): Observable<List[]> {
return this._httpClient.get<Response>('http://localhost/api/v1/lists').pipe(
map(item => item.data),
tap((response) => {
this._lists.next(response)
})
)
}
Answered By - Liel Fridman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.