Harihara_K
Harihara_K

Reputation: 164

How to receive the Map object from HTTPClient in Angular

This is the return type from rest end point:

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

How do I receive this response from Angular side?

I tried this approach:

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

I'm able to log this in the console properly. But the issue is whenever I try to fetch items from the map or fetch keys as below, it always returns undefined

requiredData.keys

Anybody know what is the issue here?

Upvotes: 0

Views: 2111

Answers (2)

kingabdr
kingabdr

Reputation: 668

In TS you can use the RECORD type to treat Maps. Try the following for your case:

requiredData: Record<String,Object[]>;

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

In your service:

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

To display the fetched data, try the following in your HTML:

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

 <div *ngFor="let object of dataObject.value">
    <!--Replace id/name with your params-->
       {{object.id}} -  {{object.name}}
 </div>

Upvotes: 1

Kavinda Senarathne
Kavinda Senarathne

Reputation: 2004

Default value that returns new HttpClient is Object. It automatically calls response.json() internally.

You can tell HttpClient what type the response will be, so:

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

Upvotes: 0

Related Questions