Search code examples
angulartypescriptangular-httpclient

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
  });

Solution

  • 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')
      });