8

Angular client - httpClient sending request

const map: Map<string, string> = new Map<string, string>();
map.set('foo', 'bar');
this.http.post(address, map, httpOptions).subscribe(
  next => console.log('next: ' + next),
  error => console.log('error: ' + error),
  () => console.log('complete')
);

Springboot server - controller receiving request

@RequestMapping(value = "/foobar", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public void fooBar(@RequestBody Map<String, String> foo){
    System.out.println(foo.entrySet());  //<-- always empty
}
0

1 Answer 1

14

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

You can convert the map as follows:

const convMap = {};
map.forEach((val: string, key: string) => {
  convMap[key] = val;
});
this.http.post(apiBaseUrl + '/foobar', convMap, httpOptions).subscribe(
      next => console.log('next: ' + next),
      error => console.log('error: ' + error),
      () => console.log('complete')
);

In the back-end, your System.out.println(foo.entrySet()); will output the following: [foo=bar]

Sign up to request clarification or add additional context in comments.

2 Comments

JSON.stringify(map) and consumes="application/json" didn't help, still empty map
Typescript map not suitable for http post calls. I used directly the json data key value pair const postBody = {"data1":var1,"data2":var2} and it works like champ.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.