matchifang
matchifang

Reputation: 5450

HttpClient post doesn't return expected type

My backend is sending data in the format of a map:

{
   "key1": ["value1", "value2"],
   "key2": ["value3"]
}

I use HttpClient.post to get the data. The data returns fine, but when I try to do data.get I got an error

this.http.post<Map<string, string[]>>(url, body).toPromise()
  .then((data: Map<string, string[]>) => {
    console.log(data);
    console.log(data instanceof Map); // false
    data.get('key1')                  // TypeError data.get is not a function
  });

Upvotes: 1

Views: 706

Answers (2)

CaspianTerrazzo
CaspianTerrazzo

Reputation: 2148

I would suggest not using Promise. Use the observable, since it is better to debug and has more featurs.

The http builds a raw JSON object, that you only can map to an object with fields. Not methods. Map is not a Model like Object. it is a "functional object". Also constructors wont be triggered

Wich means, even though you say it should be a map it is in fact a JSON object wich has no methods.

For this reason you should pipe + map the data to a Map.


this.http.post<object>(url, body)
.pipe( map(jsonObject => {
          const map = new Map<string, string[]>();
          for (const value in jsonObject) {
            map.set(value, jsonObject[value]);
          }
          return map;
        })
      ).subscribe(
        (data: Map<string, string[]>) => {
          console.log(data);
          console.log(data instanceof Map); // true
          data.get("key1");
        },
        error => console.log(error.error)
      );

Upvotes: 0

Steve Holgado
Steve Holgado

Reputation: 12071

The data returned from the network request will be a plain object, not a Map.

You can convert it to a Map though. Map takes an array of key-value pairs, so you can use Object.entries:

this.http.post<Record<string, string[]>>(url, body).toPromise()
  .then((data) => {
    const dataMap = new Map(Object.entries(data))
    dataMap.get('key1')
  });

Upvotes: 3

Related Questions