Search code examples
angularangular-httpclient

Parsing Map Object through http request in Angular


I'm very confused about something. I'm trying to send a Map<string, string[]> through a request and it is working fine in Angular 9.1 but it stopped working when I upgraded to Angular 13. I didn't find anything related to changes being made to the HttpClient or so.

I've found this issue on GitHub Serialization of JSON bodies containing a Typescript Map object: https://github.com/angular/angular/issues/32117

And the answer they provided is:

Unfortunately HttpClient uses a simple JSON.stringify call to serialize bodies to JSON. This call doesn't support what you'd like to do with Map objects.

I suggest using an HttpInterceptor to modify outgoing request bodies before they're serialized, and convert Maps to POJ(s)Os.

But I'm wondering, why am I able to successfully perform the request in Angular 9.1 but can't in Angular 13?

Here's the code example:

export interface MyObject {
  name: string;
  description: string;
  labels?: Map<string, string[]>;
}

this.http.post<AlertRule>(url, myObjectInstance).pipe(
    catchError(this.errorHandler.handlerHTTPError)
);

The problem is that the object actually sent does not contain our Map fields in Angular 13 but it does in Angular 9.

{
  "name" : "my-name",
  "description" : "my-description",
  "labels" : {}
}

Again, I know I can manually convert the Map<string, string[]> to JSON to get this working. But my question is, why this is working on an older version and why I didn't find anything related to this change in the upgrade guide? If there was one.

Could this be related to RxJS, Nodejs, or TypeScript instead of Angular?


Solution

  • This was caused because core-js@2 implemented a Map.prototype.toJSON proposal, but it was rejected by TC39, so it was removed from core-js@3.

    Reference