Passing Typescript "Map" as a part of Angular4 HTTP POST request
Asked Answered
Q

2

13

I have an Angular 4 Project where I am creating a sample Map as follows:

let sampleMap = new Map<string, string>();
sampleMap.set('key1','value1');

Now I am passing this Map as a parameter to a Angular 4 Post method which connects to a Spring Boot Rest backend as follows

Angular 4 Code:

this.http.post('http://localhost:8080/data/posturl', sampleMap).map((response: Response) => {
      return <string>response.text();
    })

Spring Boot Rest Backend Code:

@RequestMapping("/posturl")
public String launch(@RequestBody Map<String, String> sampleMap) {
    System.out.println("Received=" + sampleMap);
    return "SUCCESS";
}

Although when I try to print the 'sampleMap' as shown above, it print a blank map like follows:

Received={}

I am using Typescript version '~2.3.3' and my 'tsconfig.json' mentions target as 'es5'. Can someone please explain this behavior?

Quintana answered 15/3, 2018 at 5:59 Comment(3)
Can you have a look at the javascript? I'm not sure if it is possible to use Map with es5. I'm wondering that you don't get a compile error.Excogitate
check what do you send to the server. (I supouse that the data post is converted into some like a array ob object). Anyway I will try to convert the map into array of object before send and received as array of objectGrigson
Having the same issue. Did you find a solution eventually?Unclose
H
20

You have to convert the Map to an array of key-value pairs, as Typescript maps cannot be used directly inside a http post body.

You can convert the map as follows:

const convMap = {};
sampleMap.forEach((val: string, key: string) => {
  convMap[key] = val;
});
this.http.post('http://localhost:8080/data/posturl', convMap).map((response: Response) => {
  return <string>response.text();
})
Haydeehayden answered 27/4, 2018 at 8:50 Comment(1)
What if map is nested 5 layers inside many objects?Tinsley
N
2

You can create an object with keys as attributes. example of a map with 2 items :

let myObject = {"key1":"value1","key2":"value2"};
this.http.post('http://localhost:8080/data/posturl', myObject ).map((response: Response) => {
      return <string>response.text();
    })
Nonstandard answered 30/11, 2018 at 14:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.