0

I use the http client of Angular to retrieve data from an API. I define DTOs using typescript interfaces. One of the endpoints returns a json object which has dynamic keys which I would like to have mapped into a Map. I tried various things.

v1

export interface ItemDistribution {
  id: number;
  distribution: Map<string, number>; // I don't know the keys beforehand
}

v2

interface Distribution {
   [key: string]: number;
}

export interface ItemDistribution {
  id: number;
  distribution: Distribution; // I don't know the keys beforehand
}

But, if I call the backend with http.get<ItemDistribution>(myUrl) the result gets parsed into a JavaScript object instead. I know that I could use Object.entries(...) on an object, but is it possible to get a Map directly?

1 Answer 1

2

The key thing to understand is that when you add a type to an Angular HttpClient call, such as http.get<SomeObject>('http://api/some-end-point'), there's no mapping going on at all.

What you get back is an Object that is parsed from the JSON. That type that you specify is simply a cast, nothing actually gets converted. If the data in the JSON object doesn't match the type, there is no error or warning, it just doesn't conform to the type that your code expects, and you probably get a runtime error.

This is useful for simple objects, where the properties are limited to strings and numbers and arrays of strings, numbers, and arrays. If you have something more complex, like a Map, you need to convert that yourself from the JSON object.

So, no, you can't get a Map from the JSON object returned by your HttpClient call - you'll need to do that with Object.keys() or Object.entries() or something of the sort.

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

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.