0

I have a problem with mapping fetched JSON from the API to an existing object. TypeScript code:

enter image description here

Hero Interface:

export interface Hero {
   id: number;
   name: string;
}

Console log:

enter image description here

this.hero is always empty (undefined). How to solve this PS. I'm new in Angular and typescript.

2 Answers 2

1

It looks like the return type is an array. So you probably need to access the first element (or similar).

this.hero = fetchedHero[0];
Sign up to request clarification or add additional context in comments.

4 Comments

No, I've followed Angular tutorial and they have property initialization like hero: Hero; and I get an error: "Property 'hero' has no initializer and is not definitely assigned in the constructor." So I've marked the parameter as optional (hero?: Hero;). I think that the problem lies there...
if you look in your console.log output the response is [{...}] which is an array. followed by element 0 being displayed
Yeah, you were right. My API returns List and .ts expects one object... What an amateur. Thank you for your time!
you're welcome - that's what SO is for :-) . if you wouldn't mind accepting this as answer it'd be great - many txs
0

API was returning a LIST and ANGULAR/.ts was expecting one object. Because of that, mapping didn't succeed. After changing the return value of GET HTTP REQUEST from LIST to one object, mapping started to work!

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.