Showing Angular dropdown menu using Java HashMap

I am trying to fetch and display data from a HashMap in my Angular application by making a GET request to a Spring Application. Here is the code I have tried:

Spring code:

@GetMapping("gateways")
public ResponseEntity<?> getGateways() {
    Map<Integer, String> list = new HashMap<>();
    list.put(1, "Bogus");
    return ok(list.put);
}

Angular Service:

getContractGatewaysList(): Observable<Array<ContractGatewaysList>> {
    return this.http.get<Array<ContractGatewaysList>>(environment.api.urls.contracts.getContractGateways);
  }

Angular component:

gateways: ContractGatewaysList[];

this.contractService.getContractGatewaysList()
      .subscribe(value => {
        if (value != null) {
          this.gateways = value;
        }
      });

Interface:

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

HTML code:

<div class="form-group gateway">
    <div class="input-group-prepend">
      <label for="merchant_id">Gateway</label>
    </div>
    <select class="custom-select" name="gateway" [(ngModel)]="contract.gateway" id="gateway" required>
      <option selected>Please Select...</option>
      <option [value]="gateway.id" *ngFor="let gateway of gateways">{{ gateway.name }}</option>
    </select>
  </div>

However, I am facing an issue where the list appears empty. I need help with properly converting the Java HashMap and displaying the values in the dropdown menu. Can someone provide me with a working code example as I am stuck on this problem?

The error message I receive is:

ERROR Error: Cannot find a differ supporting object '3873648042962238500' of type 'number'. NgFor only supports binding to Iterables such as Arrays.
    at NgForOf.push../node_modules/@angular/common/fesm5/common.js.NgForOf.ngDoCheck (common.js:3152)
    at checkAndUpdateDirectiveInline (core.js:9246)
    at checkAndUpdateNodeInline (core.js:10507)
    at checkAndUpdateNode (core.js:10469)
    at debugCheckAndUpdateNode (core.js:11102)
    at debugCheckDirectivesFn (core.js:11062)
    at Object.eval [as updateDirectives] (ContractNewComponent.html:50)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:11054)
    at checkAndUpdateView (core.js:10451)
    at callViewAction (core.js:10692)

Answer №1

The Java and Spring code appears to have an issue. I am questioning whether the statement return ok(list.put) will even compile, considering that put is a method.

The error message

Error: Cannot find a differ supporting object...
seems to be a client side error and may not provide much insight if the root cause lies within the server (such as a REST API call).

Instead of attributing this problem solely to 'Angular', it would be beneficial to verify if the server is indeed returning a valid JSON object with key-value pairs.

  1. Prioritize confirming that the server is returning data correctly BEFORE delving into Angular or client-side code. Try accessing the Spring Boot REST API directly using Chrome or dedicated REST API clients like Postman.

  2. If errors persist, investigate the server side logs or exceptions in the Java and Spring environment.

  3. Refer to this example to understand how to convert a Java map object into JSON data for client consumption. Since there are various approaches in the Spring framework, consult the official documentation for more information.

  4. Once you have validated that the server side code is functioning properly, integrating Angular code should proceed smoothly.

I hope this guidance proves useful. Best of luck!

Answer №2

Your reply will look something like:

{1:"Bogus"}

Converting this flat JSON to gateways is not possible since it's an array type.

Solution:

1. To map the response JSON, you need to iterate through the keys, fetch their values, and push the data to gateways.

for (var key in responseObject) {
  console.log(key, responseObject[key]);
  // here push data `gateways`, there are plenty of tutorials on how to push data into an array
}

You can also utilize

var keys = Object.keys(yourobject);
to iterate through these keys and retrieve a specific value from your response object. The choice is yours on what implementation you prefer.

  1. You can send an angular-compatible response from Java/Spring so that it directly binds to gateways if all the structure and keys are valid.

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

Can HTML variables be accessed in lines of code before they are declared in HTML?

In line 1 of my code, I am trying to access the rowData variable which is declared in the second HTML line. However, I keep getting the error message "Property 'rowData' does not exist on type 'AppComponent'" for that line. Strangely, t ...

Resolving type error issues related to using refs in a React hook

I have implemented a custom hook called useFadeIn import { useRef, useEffect } from 'react'; export const useFadeIn = (delay = 0) => { const elementRef = useRef<HTMLElement>(null); useEffect(() => { if (!elementRef.current) ...

Develop a TypeScript utility function for Prisma

Having trouble inferring the correct type for my utility function: function customUtilityFunction< P, R, A extends unknown[] >( prismaArgs /* Make "where" field optional as it is already defined inside findUnique method below */, fn: ( pris ...

Utilizing an InjectionToken to supply another InjectionToken

I'm puzzled as to why the following code isn't functioning properly. When I manually set a string for APP_BASE_HREF, everything works smoothly. main.ts export function main(baseHref: string) { platformBrowserDynamic([ { provide: MY ...

Navigating through template files in Angular 2 components

Currently, I am working on developing a top-level component that requires an input of type @Input(): Object. This object needs to contain an array of components, which will be iterated through using *ngFor, and the templates of these components must be p ...

Error: Value Loop Detected in AngularFire Document ID

I encountered a "Cyclic Object Value" Error while working on an Angular Project with AngularFire. As a beginner with Firebase, I haven't been able to find a straightforward solution to this issue. The error arises when I query a collection in my Fire ...

Discover the geolocation data for post code 0821 exclusively in Australia using Google Maps Geocoding

I'm having trouble geocoding the Australian postcode 0821. It doesn't seem to reliably identify this postcode as being located within the Northern Territory, unlike 0820 and 0822 which work fine. Here's an example of what I'm doing: ...

Using any random function as a property value in a TypeScript React Component

I am facing a challenge in my React component where I need to define a property that can accept any arbitrary function which returns a value, regardless of the number of arguments it takes. What matters most to me is the return value of the function. Here ...

Revising a conceivably intricate template

Let's talk about managing suppliers' documents, which include code, names, and various other fields. I currently have a component export class SuppliersDetails extends MeteorComponent { supplier: any; invalidKeys: Object; // array <key&g ...

Gathering the output from every function within an array of functions

I've searched extensively for a solution to this dilemma, but have had no luck so far. Therefore, I am turning to the community for help. Please feel free to direct me to any existing similar queries. My challenge involves working with an array of fu ...

Loop through every item in Typescript

I am currently working with the following data structure: product: { id: "id1", title: "ProductName 1", additionalDetails: { o1: { id: "pp1", label: "Text", content: [{ id: "ppp1", label: "Tetetet" ...

Unable to utilize Msal Angular 9 for accessing a personalized API

I am currently attempting to integrate MSAL with Angular 9 in order to gain access to a custom 'dynamics.com' API. Although I have successfully obtained a valid access token for the login API, I am facing issues when trying to utilize this token ...

The compatibility between jQuery serialize and Angular Material tabs is not optimal

Can anyone help with an issue I'm facing? I have angular material tabs embedded within a form tag, and you can view my code example here. The problem arises when I attempt to serialize the form using jQuery in my submit function: submit(f: HTMLElemen ...

Determine the type of input and output based on another argument

When working with a function that takes an object of either TypeA or TypeB, the first parameter is used to specify the type of the object and the returned type depends on this first parameter. The issue arises in TypeScript where the type of the object is ...

Displaying errors from an API using Angular Material mat-error

I am currently working on a form that includes an email field. Upon saving the form, the onRegisterFormSubmit function is called. Within this function, I handle errors returned by the API - specifically setting errors in the email form control and retrie ...

experimenting with asynchronous promises in Jasmine to test Angular 2 services

Currently, I'm facing some challenges while testing my Angular 2 service. Even though my tests are passing, I keep encountering this error in the console: context.js:243 Unhandled Promise rejection: 'expect' was used when there was no c ...

The revalidation process in react-hook-form doesn't seem to initiate

Stumbled upon a code example here Decided to fork a sandbox version (original had bugs and errors) I am trying to implement custom validation callbacks for each form input element by providing options in the register function, but the validate is only tr ...

What is the best way to combine API calls using rxJs subscribe and map in Angular?

Currently, I am executing multiple API requests. The first one is responsible for creating a User, while the second handles Team creation. Upon creating a User, an essential piece of information called UserId is returned, which is crucial for the Team cre ...

Facing issues with module resolution while attempting to debug in VSCode

I'm currently in the process of debugging a module within our project. However, I've encountered difficulties attaching the debugger on Visual Studio Code since we recently changed the directory structure. Here is my tsconfig: { "compilerOptio ...

Uploading multiple images using AngularJS and Spring framework

I'm encountering an issue with uploading multiple images using AngularJS and Spring MVC. While I can successfully retrieve all the files in AngularJS, when I attempt to upload them, no error is displayed, and the process does not reach the Spring cont ...