Search code examples
angulardatemodelhttpclientangular14

In Angular 14, with the HttpClient library, how do I properly have my model's Date field populated from my API?


I'm using Angular 14. I have a model with a Date field

export class MyObject {
    id!: number;
    myDate! : Date;
    ...
}

I do searches for the model using the HttpClient library

import { HttpClient } from '@angular/common/http';
   ...
    return this.http.post<MyObject[]>(`${this.entitiesUrl}search`, searchObj)

The JSON returned from the API contains fields like this

[
    {
        ...
        "myDate": "2022-02-14",
        ...
    }
]

However, when I inspect my "MyObject" models, their "myDate" fields aren't Dates, they are strings. How do I get Angular or the HttpClient library to convert this field to properly be a Date?


Solution

  • Unfortunately the Angular HttpClient doesn't convert the response to an actual instance of your class by default. That is why the dates appear to be strings on your end - because they actually are. You are just getting the results of a JSON deserialization.

    One way around this is to pipe(map) the response and either create a new instance of your class with the response or convert the date fields on the response to actual date types.

    this.http.post<MyObject[]>(`${this.entitiesUrl}search`, searchObj).pipe(map((response) => {
      response.foreach((ele) => {
        ele.myDate = new Date(ele.myDate);
      })
    }))