Passing a map from the SpringBoot backend to the Angular view and storing it in LocalStorage

I'm facing a challenge with this task. I am trying to transfer a Map from my Spring Boot backend to an Angular application.

Controller

@GetMapping("/dict")
    public Map<String, String> getAll(){
        return dictionaryService.getAll();
}
@Entity
public class Entity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name = "key")
    private String key;
    @Column(name = "value")
    private String value;
public class Model {

    private Map<String, String> dict;

    public Map<String, String> getDict() {
        return dict;
    }

    public Model setDict(Map<String, String> dict) {
        this.dict = dict;
        return this;
    }
}

Service

public Map<String, String> getAll() {
       
        var model = new DictionaryModel()
                .setDictionary(StreamSupport.stream(dictionaryRepository.findAll().spliterator(), false)
                .collect(Collectors.toMap(DictionaryEntity::getKey, DictionaryEntity::getValue)));

        return model.getDictionary();
    }

In Postman I see:

{
    "key": "Some Value",
    "other-key": "Other Value"
}

I have very limited experience with Angular, but I am eager to learn and complete this task. The map fetched from the backend needs to be stored in localStorage and then displayed in the view based on the key-value pairs. I am struggling with finding the right approach. Can anyone offer some guidance or maybe a sample solution?

Your help is greatly appreciated!

Answer №1

Your Angular service implementation may look something like this:

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class YourService {
  constructor(private readonly _http: HttpClient) {}

  getDictMap(): Observable<{
    'key',
    'other-key',
  }> {
    return this._http.get<any>('/dict').pipe(
      map(res => res)
    );
  }
}

You can then store the data retrieved by the service in localStorage within your component:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
})
export class YourComponent implements OnInit, OnDestroy {
  private sub: Subscription;
  public dict: { key, value }[];

  constructor(private yourService: YourService) {}

  ngOnInit() {
    this.sub = this.yourService.getDict().subscribe({
      next: res => {
        this.dict = Object.entries(res).map(([k, v]) => {
          return { key: k, value: v };
        });
        localStorage.setItem('dict', JSON.stringify(this.dict));
      },
      error: err => {
        console.error('An error! ', err);
      }
    });
  }

  ngOnDestroy() {
    if (this.sub) {
      this.sub.unsubscribe();
    }
  }
}

In your Angular template file, you can display the stored data as follows:

<div *ngIf="dict">
  <div *ngFor="let elem of dict" class="card">
    {{elem.key}}: {{elem.value}}
  </div>
</div>

If you are unsure about the keys of the object in your dictionary, you can modify the output Observable accordingly:

getDictMap(): Observable<object> {

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

Angular Error: Property 'map' is not found in type 'OperatorFunction'

Code: Using map and switchMap from 'rxjs/operators'. import { map, switchMap } from 'rxjs/operators'; Here is the canActivate code for route guard: canActivate(): Observable<boolean> { return this.auth.userObservable ...

Saving a .JSON file with Java ME

After successfully converting java to json using toJSON(), I'm now wondering how I can save that json data as a .json file. Any suggestions or tips on how to accomplish this? I am currently utilizing Blackberry and Java ME for my project. If anyone h ...

Node-server hosted in Azure experiencing difficulties with websockets connectivity

I have a simple example that works fine on my local machine but fails to work properly when deployed on Azure. The original issue I had related to a CORS error, which I have since resolved by editing it out. However, I am still struggling to get WebSockets ...

The response code in the API remains 200 despite setting the status code to 204 in NestJS

I have developed an API that needs to return a 204 - No Content Response import { Controller, Get, Header, HttpStatus, Req, Res } from '@nestjs/common'; import { Response } from 'express'; @Get("mediation-get-api") @Head ...

Restrain a Key according to the data type of its value within a universal category

I am currently working on creating a versatile function where the generic type is used to define its parameter. Here's an excerpt from this parameter : type Configuration<T> = { masterdata: T[], target: ???? } I am encountering difficu ...

struggling to locate my element in Selenium (novice user)

Greetings all, I am an aspiring programmer who is venturing into the realm of creating a cookie clicker bot with the help of Selenium. For those unfamiliar, Cookie Clicker is an addictive web-based game that you can check out here. My current challenge in ...

Waiting for variable to become false using Angular 7 Observable

The observable below highlights the authentication process: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { CookieService } from 'ngx-cookie-service'; import { Observabl ...

Bring in properties from a separate file in Vue3

Currently, I am utilizing Vue3 along with the options API. Within my setup, there are various Vue components that rely on a shared prop defined as: exercise: { type: Object as PropType<Exercise>, required: true, }, To streamline this pro ...

What is the best way to link assets within an Angular custom element (Web Components)?

After successfully creating a web component and referencing an image from my asset folder, everything was running smoothly on my local environment. However, when I published my custom element to Firebase hosting, I encountered some issues. When trying to ...

What steps should I take to prevent my <mat-card> from expanding whenever messages are shown in Angular 9?

I have a <mat-card> containing a login form on my page. However, when error messages are displayed, the vertical size of the <mat-card> changes and I need it to remain the same. Is there a way to prevent this from happening? Below, you will ...

How can I parse and create object from a String returned by an API that throws an error stating "is not a JSONObject" in Java?

This is the request: https://api-pub.bitfinex.com/v2/candles/trade:1h:tBTCUSD/hist?limit=2 Here is the response: [[1607630400000,18399,18415,18450.367075,18399,279.63699634], [1607626800000,18290.48824022,18399,18400,18255,190.53601166]] I was informed ...

Error encountered while retrieving information from Excel spreadsheet resulting in a NullpointerException

I keep encountering a NullPointerException while trying to read data from an excel sheet at cell index = 6. I added a while loop with while(value != null) to handle null values, but the exception persists without any output being generated. I have attach ...

The NgRX Effect is malfunctioning

Working on integrating ngrx with Angular. Authentication is successful, but facing issues with product store implementation: Organizing the project using modules: const routes: Routes = [ { path: '', redirectTo: 'home', ...

What sets apart :host::ng-deep .class from .class :host::ng-deep?

Can you explain the distinction between the following two lines of code in scss, Provide some sample snippets as examples. :host::ng-deep .content-body { ... } and .content-body :host::ng-deep { ... } ...

Getting the error message ""Cannot return null for non-nullable field" while trying to subscribe in NestJS using GraphQL"

I have developed a Node.js backend using Nestjs and incorporating Graphql, with my frontend built on Ionic/Angular utilizing Apollo-angular for graphql functionalities. However, I am encountering difficulties in subscribing to data additions or changes. St ...

Discovering a hyperlink using Selenium: A step-by-step guide

Here's a question: How can I use the Selenium JAVA API to locate a link in the given scenario: The link does not have an ID There are numerous links, each with a unique href value I have some specific information (substring) about the href of the li ...

Show the CustomError message and HTTP status code that was raised by the server in the HttpErrorResponse

I am in the process of developing an ASP.NET Core API server paired with an Angular client. One of my main objectives is to ensure that the client can effectively capture any exceptions thrown by the server. I have implemented an HTTP Interceptor in Angula ...

Adding Rust to an OpenJDK Docker image

I've been working on creating a dockerfile to run a rust test suite that needs a jar running on a separate port. I have the jar file stored in the project folder and plan to begin with an openjdk docker image, then download rust for testing purposes. ...

Displaying centered text over a mat-progress-spinner using Angular, Material, and Flex-Layout

In my Angular project, I am utilizing material and flex-layout. One challenge I encountered is centering text inside a mat-progress-spinner element. I attempted to achieve this by using position absolute, but the issue is that it doesn't stay centered ...

Stop non-logged-in users from accessing page content rendering

Lazy loading is being used in my application to render pages. { path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule', canActivate: [AuthGuard] } The problem arises when the user types www.mydomain.com/dashbo ...