When processing JSON data, Typescript is unable to interpret a map<string,string> structure

I am currently working with Angular5 within a spring boot application and I am attempting to retrieve a Map object in JSON format.

Spring :

//sample method
return ResponseEntity.ok((new Gson()).toJson(/*My map object*/));

Angular5 :

sql_list = new Map<string,string>();
this.myService.getQueries().subscribe(
    data => {
        console.log("Data Received: ");
        console.log(data);
        this.sql_list = data;
        console.log(this.sql_list.get("query1"));
    } 
);

When inspecting the client side, I can confirm data reception using console.log:

Data Received:
{
  "query1" : "select * from test",
  "query2" : "select * from test2",
  "query3" : "select * from test3"
}

However, when attempting to utilize the map.get(string key) method on the sql_list object, it results in the following error:

ERROR TypeError: _this.sql_list.get is not a function

What error have I made here?

EDIT: Upon following Florian's suggestion, the issue was resolved:

this.sql_list = new Map<string, string>(Object.entries(data));

Answer №1

Florian pointed out the error of assigning a plain JSON object to a variable that should be of type Map. If you really want it to be a Map, you can achieve this by iterating through the keys in the data object like below:

for (const key in data) {
    this.sql_list.set(key, data[key]);
}

This code snippet will go through all the keys ('query1', 'query2', 'query3') and set their corresponding values in your map.

I'm curious about why you're opting for a Map. If you already know the structure and fields of your object, consider defining a class representing it for better type safety and clarity.

Just a suggestion. It may also enhance your coding experience with features like autocomplete in tools like VS Code.

Answer №2

When you start coding, you initialize a Map:

sql_list = new Map<string,string>();

However, as you progress to the data handler section, you end up replacing this map with the incoming data:

this.sql_list = data;

Since the variable data is typically an object returned by the HTTP handler, it may not adhere to the Map structure and lack functionalities like get. Instead, it will likely be a basic JavaScript object that can be accessed using syntax like console.log(sql_list['query1']).

To address this issue, you could employ a strategic combination of Object.keys() and set() on your initial empty Map stored in

sql_list</code), effectively "transforming" the raw JavaScript object <code>data
into a comprehensive Map object.

Answer №3

Once you set this.sql_list = data, the previous value of sql_list is replaced, converting it from a Map<string, string> to a plain javascript object due to the nature of data.

In most scenarios, utilizing Map<string, string> instead of regular objects is not necessary since object values can be accessed through indexing such as sql_list['query1']. In typescript, if this functionality is desired, one must declare sql_list as an any type or create a custom type like a string mapper type:

interface strMap {
  [key: string]: string;
}

Simply declare sql_list: strMap; to implement this.

If there is a valid reason for using Map<string, string>, reference this question for further insights.

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

What is the best way to set up a property in a service that will be used by multiple components?

Here is an example of how my service is structured: export class UserService { constructor() {} coords: Coordinates; getPosition() { navigator.geolocation.getCurrentPosition(position => { this.coords = [position.coords.latitude, posit ...

Creating a Redis client in Typescript using the `redis.createClient()` function

I'm currently trying to integrate Redis (v4.0.1) into my Express server using TypeScript, but I've encountered a small issue. As I am still in the process of learning TypeScript, I keep getting red underline errors on the host parameter within th ...

How can I access this document using Java?

Can someone assist me in retrieving JSON body documents like this from MongoDB? { "question":"what is your favorite color?", "choices":[{"option":"yellow"},{"option":"blue"},{"option":"green"}], "creation-date":"2014-04-13", "expiry date":"2014-04-14" } ...

Retrieving data with jSON through the local storage API

Seeking assistance with a problem I'm facing. Being new to this, the textbook Headfirst into programming isn't very helpful in explaining. After researching on stackoverflows, I'm still struggling. Any guidance would be greatly appreciated. ...

Connecting text boxes with JavaScript and JSON for gaming experience

I am currently developing a game and have encountered a slight issue. Currently, there is a text box in the game that prompts the player to run into it to progress to the next level. When the player does so, the next level loads seamlessly, which works per ...

The process of deserializing JSON in an API function is successful when initiated from Visual Studio or a browser, but encounters issues when

In my VB project, I have the following class within an ASMX service: Public Class cName Public Property nameOrAlias As String Public Property nameType As String Public Property isVerified As String Public Property nameID As String Publ ...

The art of linking Observables on the fly in rxjs and angular

In my current project, I am facing a challenge where multiple events can be triggered from an object. These events are handled by a component and then sent to a REST API. The issue arises when I need to ensure that calls to the REST API for a specific reso ...

Is there a source where I can access a pre-populated json file specifically designed for testing purposes?

Currently, I am developing a new application that requires importing JSON data. I am in need of testing with about 10,000 entries, however, I do not want to manually create a JSON string with that many entries. If anyone knows where I could access pre-po ...

What is the best way to generate a Searchstring for the Google AJAX Search API?

Currently, I am using this code to retrieve search results from an API: querygoogle.php: <?php session_start(); // The code below is used to fetch search results from the Google AJAX Search API $url = 'http://ajax.googleapis.com/ajax/services/s ...

Tips on handling json files and constructing an lstm model?

I'm currently working on implementing LSTM on the HP news dataset, which is stored in JSON format (). I attempted to run this code and encountered errors. I'm unsure what's causing the issue with this code? from keras.layers import LSTM, Act ...

Unable to send a Json Array in the body of a Restassured request - encountering java.lang.IllegalStateException: The content is not a valid JSON Object

I'm attempting to send a list of objects as the body in a restassured request: Transaction transaction1 = new Transaction(); Transaction transaction2 = new Transaction(); List<Transaction> transactionList = new ArrayList<Transaction>(); t ...

A guide on extracting an integer value from JSON data using Qt

Is there a way to retrieve the integer value from a QJsonValue object? Let's say we have the following JSON data: { "res": 1, "message": "Common error" } We want to extract the value of "res" from this data, so we attempted t ...

The enigma of TypeScript

Whenever I try to declare or initialize data members in a class, the following methods never seem to work: var view: string[]; var view: string[] = []; let view: string[]; let view: string[] = []; Even though the TypeScript documentation states that it s ...

Retrieve JSON data from Localhost

I'm facing an issue trying to retrieve JSON data from http://localhost:3000/clientes in Angular 5 and display it in a table. Currently, I can only load the JSON into a table when it's located in the /assets/ directory. This is the code snippet ...

What triggers the execution of the catch method while chaining HTTP promises?

In my Angular application, I have developed a custom loaderService that displays a loading spinner while the back-end processes requests. Below is the code snippet: export class ComponentOne { constructor(loaderService: LoaderService, orderService: Orde ...

Guide on transforming application/atom+xml response to JSON using REST template

I am currently working with atom/xml data and need to convert it into a Java object. However, I'm encountering an error during the conversion process. Here is the code snippet: ResponseEntity<BusinessPartner> response = restTemplate.exchange( ...

The parameter value of "[[email protected] ]" does not align with the expected data type of java.lang.Long; thus resulting in a java.lang.IllegalArgumentException as the nested

UserController.java class If I eliminate the "required=false" attribute, the error persists. @RequestMapping(value= "/login", method = RequestMethod.POST) public String login(@RequestParam(value= "email", required = false) String email, @RequestParam(valu ...

Combining various POST requests by matching the common value in each array. (Angular)

Here are the two different sets of data: "statusCode": 200, "data": [ { "color": { "id": "1111", "name": null, "hex&quo ...

Controlling a generic interface's acceptance of certain data types in typescript: a guide

Is there a way to restrict a generic interface from accepting specific data types in TypeScript? I understand that I can define acceptable data types for a generic interface in TypeScript. interface exampleInterface<T = void | any>; But what if I w ...

How to create an array of objects using an object

I have a specific object structure: { name: 'ABC', age: 12, timing: '2021-12-30T11:12:34.033Z' } My goal is to create an array of objects for each key in the above object, formatted like this: [ { fieldName: 'nam ...