1

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

  1. How I can explain this?
  2. What is the correct way to do the job?

Thank you

1
  • You tell typescript-compiler that there is an array comming from get-ressource. so you would need to access like item[0].data or turn array into single ICategory - do the last option if the Get result is actually like you have shown in first json. Commented Dec 6, 2019 at 22:13

2 Answers 2

2

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[]}>

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

2 Comments

data is not a property of ICategory, this is why I added map() in order to get rid of data and directely access the array. But not sure I master well this operation
You could try like this then: this.http.get<any>(this.categoryUrl + prop).pipe( tap(data => console.log(JSON.stringify(data))), map(item=>(item.data as ICategory[])); ); }
1

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).

Comments

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.