英文:
In Angular 14, with the HttpClient library, how do I properly have my model's Date field populated from my API?
问题
我正在使用Angular 14。我有一个带有日期字段的模型
export class MyObject {
id!: number;
myDate! : Date;
...
}
我使用HttpClient库对模型进行搜索
import { HttpClient } from '@angular/common/http';
...
return this.http.post<MyObject[]>(`${this.entitiesUrl}search`, searchObj)
从API返回的JSON包含这样的字段
[
{
...
"myDate": "2022-02-14",
...
}
]
然而,当我检查我的"MyObject"模型时,它们的"myDate"字段不是日期,而是字符串。如何让Angular或HttpClient库将此字段正确转换为日期?
英文:
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?
答案1
得分: 1
抱歉,以下是翻译好的部分:
"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."
"不幸的是,Angular HttpClient 默认情况下不会将响应转换为您的类的实际实例。这就是为什么日期在您这端看起来像字符串的原因 - 因为它们实际上确实是字符串。您只是得到了JSON反序列化的结果。"
"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."
"解决这个问题的一种方法是使用pipe(map)对响应进行处理,然后使用响应创建您的类的新实例,或者将响应中的日期字段转换为实际的日期类型。"
"this.http.post<MyObject[]>(${this.entitiesUrl}search
, searchObj).pipe(map((response) => {
response.foreach((ele) => {
ele.myDate = new Date(ele.myDate);
})
}))"
"this.http.post<MyObject[]>(${this.entitiesUrl}search
, searchObj).pipe(map((response) => {
response.foreach((ele) => {
ele.myDate = new Date(ele.myDate);
})
}))"
英文:
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);
})
}))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论