Decoding Dynamic JSON Data into a Map Using Angular

When working with Angular's http client to fetch data from an API, I create DTOs using typescript interfaces. One of the endpoints returns a JSON object that contains dynamic keys which I want to map into a Map. After trying out different approaches,

Version 1:

export interface ItemDistribution {
  id: number;
  distribution: Map<string, number>; // Keys are unknown beforehand
}

Version 2:

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

export interface ItemDistribution {
  id: number;
  distribution: Distribution; // Keys are unknown beforehand
}

However, when I make a call to the backend using

http.get<ItemDistribution>(myUrl)
, the result is parsed into a JavaScript object instead. While I am aware that I could use Object.entries(...) on an object, I am curious if there is a way to directly retrieve a Map?

Answer №1

It's important to note that specifying a type in an Angular HttpClient call, such as

http.get<SomeObject>('http://api/some-end-point')
, does not involve any sort of mapping process.

When you receive the response back, it is simply an Object parsed from the JSON data. The type specified acts as more of a cast rather than a conversion. If the JSON data does not align with the specified type, there won't be an error message – the data just won't match the expected type, possibly causing a runtime error.

This method works well for simple objects containing strings, numbers, and arrays of such types. For more complex structures like Maps, you'll have to handle the conversion yourself from the JSON object.

In conclusion, extracting a Map directly from the JSON object returned by an HttpClient call isn't possible; additional steps using methods like Object.keys() or Object.entries() are necessary.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When a function containing multiple statements is utilized to generate a template string for an angular component, an error may occur indicating that the value cannot be statically determined

I'm experimenting with creating my component template dynamically using the following approach. import { Component } from "@angular/core"; function getTemplate() { let temp = ""; for (let index = 0; index < 5; index++) { ...

Is it possible to insert data into SQL Server from an Angular application without relying on .NET Core?

Is there a way to extract data from an Angular-made form and store it in a SQL Server table without the need for .NET Core? ...

How to Restrict the Number of Rows Displayed in an Angular 4 Table

Currently, I am faced with a situation where I have a lengthy list of entries that I need to loop through and add a row to a table for each entry. With about 2000 entries, the rendering process is slowing down considerably. Is there a way to limit the disp ...

Alerts created with the AlertController in Ionic 4 Angular are not displaying the message when the

After creating a reliable alert service for my Ionic 4 project, I encountered an issue when building the release version of the app. Despite functioning perfectly in other environments like "ionic serve" and "ionic cordova emulate", the message part of the ...

Show Index of an Array in Angular version 4 and above

I have implemented a drag and drop feature where elements are dragged and dropped into an array. The dragging functionality is contained in one component, with three different types of fields - text, number, and date - that can be dragged onto the form. On ...

The most efficient method for receiving real-time updates from the server to the app is through Angular 7

Currently, I am in the process of developing an Angular 7 messages service (user to user) for my website. The approach I have taken involves receiving updates from the server (Yii2 REST API) every 3 minutes using an interval function (see code snippet belo ...

Issue with sending headers in HttpClient.post method in Angular 8

I have successfully implemented the following code: this.http.post (TGT_IP,body, {responseType: 'arraybuffer'}).subscribe( (val) => { console.log("POST call successful value returned in body", val); ...

Using conditional statements to localize in Angular

In my Angular application, I am utilizing i18n for internationalization purposes. When it comes to HTML, I use i18n="@@<unique_Id>" and for dynamic elements defined in TypeScript class files, I use $localize. For example: this.buttontext = ...

What is the process for modifying the values within a BehaviorSubject<object>?

Assuming we have a BehaviorSubject<object> intelligentObject = new BehaviorSubject<object>( {property1: data1, property2: { subProperty1: info1, subProperty2: info2}, ...} ); Is there a way to modify each value and add new properti ...

Making the Angular 2 Http Service Injectable

I am fetching a large object from my server using an Angular 2 service when the website loads. The structure of the data I need to fetch is as follows: { Edu: [...], Exp: [...], Links: [...], Portfolio: [...], Skills: [...] } Here&apo ...

What is the best way to link multiple select tags in an HTML document?

I am working with a data grid that contains student information such as Name, Class, and Score. Each row has a checkbox for selection. The requirement is that when the user selects one or more rows and clicks on the "show information" Button, a new windo ...

Break down the key:value objects into individual arrays

I'm currently working on an ionic project that involves handling an incoming array composed of key:value objects such as the one shown in the image below: https://i.stack.imgur.com/qrZiM.png My question is, can these values be separated into three d ...

Setting up the environment variable for ApolloClient to be utilized in server-side rendering for continuous integration/continuous deployment involves following a specific

My apolloClient is configured as follows: /** * Initializes an ApolloClient instance. For configuration values refer to the following page * https://www.apollographql.com/docs/react/api/core/ApolloClient/#the-apolloclient-constructor * * @returns Apoll ...

Add a new class to clr-tab

Currently, I am attempting to display Clarity tabs in a horizontal layout as opposed to the vertical layout due to the unavailability of vertical tabs. Just to clarify, the links are displayed vertically while the main structure consists of horizontal link ...

Why is TypeScript resorting to using 'any' for specific prop type definitions in React?

Having some trouble with my props typing: export interface ITouchable { isDisabled?: boolean; margin?: Margin; height?: number; bgColor?: string; } The definition of Margin is as follows: type Margin = | { top?: number; bottom?: nu ...

Preventing duplicate namespace declarations in TypeScript

Let's say I have a variety of objects with the following data structure: { namespace: 'first'|'second'|'third' } Now, I need to include another object with the same data structure, but its namespace cannot be assigned ...

Unable to use console log in shorthand arrow function while working with Typescript

When debugging an arrow function in JavaScript, you can write it like this: const sum = (a, b) => console.log(a, b) || a + b; This code will first log a and b to the console and then return the actual result of the function. However, when using TypeSc ...

When evaluating code with eval, properties of undefined cannot be set, but the process works seamlessly without

Currently, I am attempting to utilize the eval() function to dynamically update a variable that must be accessed by path in the format myArray[0][0[1][0].... Strangely enough, when I try this approach, I encounter the following error: Uncaught TypeError: ...

How to link Array with Observable in Angular2 Typescript without using .interval()

Is it possible to achieve the same functionality without using the "interval()" method? I would like to link an array to an observable, and update the array as well as have the observable monitor the changes. If this approach is feasible, how can we inco ...

Tips for implementing a decorator in a TypeScript-dependent Node module with Create-React-App

I am working on a project using TypeScript and React, which has a dependency on another local TypeScript based project. Here are the configurations: tsconfig.json of the React project: "compilerOptions": { "target": "esnext& ...