Reputation: 619
CONTEXT
An Angular 8 application requests for an external web api.
The GET request result is something like that:
{
"data": [
{
"name": "QWERTY",
"isValid": false
}]
}
I am calling the api with this TypeScript code in my service:
private categoryUrl = 'http://localhost:8081/api/categories?OrderBy=';
return this.http.get<ICategory[]>(this.categoryUrl + prop )
.pipe(
tap(data => console.log(JSON.stringify(data)))
,map(item=>item.data)
);
}
MY PROBLEM
This line of code doesn't compile claiming:
error TS2339: Property 'data' does not exist on type 'ICategory[]'
If I comment the map() line and run it's compiling and the web application starts, but no data are displayed on the html template.
If then I uncomment without stopping, the application recompile, send the same error message. But the request is done correctly and I can see my result on the template.
MY QUESTIONS
Thank you
Upvotes: 1
Views: 473
Reputation: 1847
You are probably just getting a type check error. What are the properties in the class ICategory
?
When you do this.http.get<ICategory[]>
, the HTTP response is expected to follow the interface of ICategory
. Check if data
is a property in ICategory
, amend accordingly.
If ICategory
should be the actual data in the array 'data'. You can either omit the Generic type or use a correct interface for it: this.http.get<{ data: ICategory[]}>
Upvotes: 2
Reputation: 691645
Look at the JSON you receive. It starts with {
. So it's not an array. It's an object.
But look at your code:
this.http.get<ICategory[]>
This tells TypeScript: trust me, the response body is an array of ICategory objects.
So you need to pass the correct generic type to http.get()
. You haven't tols how ICategory is defined, so I have no idea of what this type should be (other than by defining it myself based on the JSON of course).
Upvotes: 1