Ways to obtain the Map object from HTTPClient in Angular

When calling a REST endpoint, the return type is as follows:

ResponseEntity<Map<String, List<Object>>>

How can I handle this response on the Angular side?

I attempted the following approach:

let requiredData = new Map<String, Array<Object>>();
 this.service.getMap().subscribe((mapData) => {
      requiredData = mapData;
}

I am able to successfully log this in the console. However, when I try to retrieve items from the map or fetch keys as shown below, it always returns undefined

requiredData.keys

Does anyone know what the issue might be here?

Answer №1

If you're working with TypeScript, the RECORD type can be used to handle Maps effectively. Here is a solution tailored to your specific situation:

requiredData: Record<String,Object[]>;

this.service.getMap()
.subscribe((mapData: Record<String,Object[]>) => {
        this.requiredData= mapData;
      });

In your service file:

getMap(): Observable<Record<String,Object[]>> {
      return this.http.get<Record<String,Object[]>>(
        'your endpoint'
      );
    }

To render the retrieved data on your HTML page, consider the following approach:

<ng-container *ngFor="let dataEntry of requiredData | keyvalue">
   <p>This is the string key : {{ dataEntry.key }}</p>

 <div *ngFor="let item of dataEntry.value">
    <!--Replace id/name with your desired parameters-->
       {{item.id}} -  {{item.name}}
 </div>

Answer №2

When you obtain a new HttpClient instance, the default return value is an Object. This HttpClient will automatically execute the response.json() method internally.

To specify the expected type of response from HttpClient, you can do the following:

this.httpClient.get<User[]>(...)
 .map((users) => {
   ...

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

Is it possible for a TypeScript function to be used as a React prop even if it conflicts with the function signature's in

Why does the TypeScript type checker allow a prop with a function parameter that does not strictly match the definition? For example, I have a function called callbackImpl = (str: string): number, which is passed as a React prop parameter defined as callb ...

Angular 4 - Seeking clarification on the usage of *ngComponentOutlet

When using *ngComponentOutlet, the following code snippets are employed to handle the displaying: Below is a snippet of functional code: this.displayComponent({ 'objects':[ {component: ToDisplayAComponent, expanded: fals ...

I am curious about the significance of the "=>" symbol within the Ionic framework

I utilized the documentation provided on the Ionic website to incorporate Firebase into my mobile application. this.firebase.getToken() .then(token => console.log(`The token is ${token}`)) // store the token server-side and utilize it for sending not ...

Replace i18next property type in React for language setting

We have decided to implement multilanguage support in our app and encountered an issue with function execution. const someFunction = (lang: string, url: string) => any If we mistakenly execute the function like this: someFunction('/some/url', ...

Creating a function in typescript that returns a type based on the input parameter

type A = { aa: string; bb: number; }; type G = { <T extends keyof A>(a: T): A[T]; <T1 extends keyof A, T2 extends keyof A>(a: T1, b: T2): [A[T1], A[T2]]; // ... }; const g = {} as G; const x = g('aa'); //string const y = g ...

What is the best way to determine which variable holds the greatest value in Angular?

I am working with different array lengths stored in variables and trying to determine which variable is the greatest, then change the font color of that variable. However, I encountered an issue where if two variables have the same value, only one is being ...

You cannot invoke this expression while destructuring an array of React hooks in TypeScript

Within my React TypeScript component, I have several fields that check a specific condition. If the condition is not met, the corresponding field error is set to true in order to be reflected in the component's DOM and prevent submission. However, whe ...

Primary source for recurring components with the @SkipSelf decorator

Trying to understand the inner workings of Angular's dependency injection system, it seems that the component instance tree is traversed to locate the first occurrence of the specified provider, giving priority to ElementInjector over ModuleInjector ( ...

Wondering how to leverage TypeScript, Next-redux-wrapper, and getServerSideProps in your project?

Transitioning from JavaScript to TypeScript for my codebase is proving to be quite challenging. // store.ts import { applyMiddleware, createStore, compose, Store } from "redux"; import createSagaMiddleware, { Task } from "redux-saga"; ...

Authentication and account system with .NET Core Backend and Angular2 Frontend for seamless user login and security measures

I've hit a roadblock in the initial stages of my new project, specifically with setting up account management. My project involves using Angular2 on the frontend, connected to a .NET Core WEB API & Backend that interfaces with a MySQL database via En ...

Is it possible to enhance an external class with a non-static method using prototypes?

Is it possible to use prototypes to add a function for a class instance? allowing me to access this or __proto__ keyword inside my method, like so: class PersonClass { name: string; constructor(name: string) { this.name = name; } sayHello() ...

Tips for integrating an angular module that lacks Universal compatibility into an angular/cli application with server-side rendering (SSR) support

Greetings everyone! I've been working on developing an Angular app that utilizes Universal with SSR for quite some time now. At times, while including a module like ngx-editor, I noticed that the server would fail silently without any indication of wh ...

Dragging and dropping in Angular does not move to the intended location within a mat dialog

Attempting to manipulate the order of a lengthy list by dragging and dropping items. In a basic component, moving an item is uncomplicated - able to drag it anywhere within the list. While dragging, can scroll through contents beyond visible range and dro ...

Error encountered in Angular 17 SSR: Importing module "@angular/ssr" does not have the exported member "REQUEST"

I'm having trouble getting cookies on Angular 17 with SSR. In the past, I was able to use the REQUEST pulled from @nguniversal/express-engine/tokens, but now with @angular/ssr, I can't find where to pull REQUEST from. import { REQUEST } from &apo ...

Generating mat-option elements using ngFor on an empty initialized list

How can I dynamically update the values in the "specialisation" mat-select when a skill is selected in the "competence" mat-select? I have tried using [(ngModel)] to link my variable with the model, but it doesn't seem to update the list. I attempted ...

Wait for the nested request to finish before returning the Observable

There are a pair of POST-requests within this function: function addArticle(request: IArticle) { const requestPath = `${this.backendUrl}/articles`; return this.http .post<IResponse<IArticleApiContract>>(requestPath, getArticleApiContra ...

Removing Bootstrap Styles in Angular Single Page Applications

Currently, I am in the process of customizing the styles for an ASP.Net Core 2.2 Angular SPA. Upon examination, I noticed that a specific file webpack:///./node_modules/bootstrap/scss/_reboot.scss is being generated at runtime. To take control of the styl ...

Redirecting to an Unverified Website

I encountered an issue in my service.ts file where VeraCode code scan is failing Flaws by CWE ID: URL Redirection to Untrusted Site ('Open Redirect') (CWE ID 601)(16 flaws) Description The web application is vulnerable to URL redirection attacks ...

How to access the selectedIndex and handle click events for select options in Angular4

Initially, my aim was to get the selectedIndex and then retrieve the selected data model, but I discovered that I could directly access the selected data model in Angular2 RC2 by following this link: Angular2 RC2 Select Option selectedIndex. However, I e ...

Tips on updating x-label formatting (to display months in words) utilizing morris.js with Angular 5

Snapshot of my Request. I'm looking to alter the xLabel (2018-01 - to - Jan) and I am utilizing morris.js. ...