Return a HashMap from HTTP GET using angular 10

Viewed 700

I am using following version. Angular CLI: 10.0.1

Node: 12.18.2

OS: win32 x64

Angular: 10.0.2

I have a Java spring boot service (working well) which returns the data as a HashMap.

Map<String, List<String>>

Following is the output of the service call:

// 20200728103825
// http://localhost:1234/config-data

{
  "books": [
    "ABC",
    "PQR",
    "XYZ",
    "QWT",
    "LMN",
  ],
  "categories": [
    "FICTION",
    "DRAMA"
  ]
}

I also have a simple call which returns list of books (as String). E.g.

// 20200728112259
// http://localhost:1234/book-data

[
  "ABC",
  "PQR",
  "XYZ",
  "QWT",
  "LMN",
]

Now, I want to use this in my Angular code.

I have the service defined as follows.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(
    private http: HttpClient
  ) { }


  loadBookData(){
    console.log("loadBookData Service");
    return this.http.get<string[]>('http://localhost:1234/book-data');
  }

  loadConfigData() {
    console.log("loadConfigData Service");
    // Looking for help here
  }

}

Basically I am able to read the book-data (string[]).

However, how should read complex data which is HashMap from service?

1 Answers

you can declare a model like this:

 export class Result{
    books: string[];
    categories: string[];
} 

your loadConfigData should be as follows:

  loadConfigData() {
    console.log("loadConfigData Service");
        return this.http.get<Result>('http://localhost:1234/config-data')
                .pipe(
                  map((data:Result) => {
                    console.log(data.books);
                    console.log(data.categories);
                  })
                 );

  }
Related