ASP.NET Core 7 Web API:Angular 表单控件的日期序列化

问题描述 投票:0回答:1

我一直在 Stack Overflow 和整个网络上搜索,但我似乎找不到直接的答案。

Person
类中,
Birthday
定义为
DateTime

public class Person
{
    public string Name { get; set; }
    public DateTime Birthday { get; set; }
}

在我的控制器中,我有一个端点,如下所示:

[HttpGet("personId")]
public async Task<ActionResult<Person>> GetPerson(int personId) 
{
    var person = new Person 
                     {
                         Name = "Joe Blow",
                         Birthday = DateTime.Now
                     };
  
    return Ok(person);
}

当我通过 Postman 到达端点时,我得到:

{
    "name": "Joe Blow",
    "birthday": "2023-08-07T07:37:17"
}

好吧,太棒了。

DateTime
被序列化为这种格式。我相信它被称为 ISO 8601,但这对我来说真的不重要。

重要的是,当我将其放入响应式表单 FormControl 中时,它被视为 Javascript 日期,而不是字符串。

如果我首先将其替换为 JS Date,它就可以工作:

person.birthday = new Date(person.birthday);

但我真的很讨厌这样做。我在这里缺少什么?

真正烦人的部分是,在我的 Angular 代码中,我明确声明

Person.birthday
Date
:

export class Person {
    name: string;
    birthday: Date;
}

所以当我使用HTTP客户端获取一个人时:

this.httpClient.get<Person>(url).pipe(take(1)).subscribe(
  {
    next: (result: Person) => {
      console.log('Surpise: result.birthday is a string!');
    }
  }  
);

预先感谢您的帮助。

angular angular-reactive-forms .net-7.0 asp.net-web-api-routing
1个回答
0
投票

你不会错过任何东西:来自 API 的日期总是作为字符串返回(认为不能作为 JavaScript 对象返回)。

我个人解决了这个问题,在我的服务中制作了一个简单的“地图”。通过这种方式,你的角度组件始终在 Date javaScript 对象上工作

getData()
{
    return this.getUrl(...).pipe(map(res:any[])=>{
       res.forEach(x=>{
          x.propertyDate=new Date(x.propertyDate)
       })
       return res;
    }
    )
}

getDataId(int id)
{
    return this.getUrl(...).pipe(map(res:any)=>{
      res.propertyDate=new Date(res.propertyDate)
      return res;
    })
}

saveData(data:any)
{
     const dataSend:any={...data} //make a copy to not transform the origina data
     dataSend.propertyDate=data.propertyDate.ToString()
     return http.post(....,dataSend)
}
© www.soinside.com 2019 - 2024. All rights reserved.