Angular 在 POST 请求中序列化具有特定格式的日期

use*_*037 6 json date json-serialization angular angular7

我是 Angular 的新手,对于序列化添加到 POST 请求的对象的 Date 属性的最佳方法是什么有几个疑问。给定样本类

export class MyClass{
    public dateProperty: Date;
}
Run Code Online (Sandbox Code Playgroud)

我在服务中有以下代码:

public addMyClass(myClass: MyClass): Observable<MyClass> {
    return this.http.post<MyClass>(this.apiBaseUrl, myClass);
}
Run Code Online (Sandbox Code Playgroud)

我必须按以下格式序列化日期'yyyy-MM-dd hh:mm'。我考虑了不同的方法,例如定义装饰器(如果可能)或重写toJson()方法,但我不知道这些是唯一的选择还是有更好的解决方案......

San*_*gão 7

描述我遇到的问题,例如,我当时在 GMT+1,只想保存日期,例如“2019-04-28T00:00:00 GMT+01:00”,并且 JSON 序列化是将日期更改为“2019-04-27T23:00:00.000Z”。基本上发送了错误的日期,我猜你也面临着类似的事情。

我发现在将整个项目发送到服务器之前需要等待一次自定义序列化所有内容,这是通过覆盖数据对象上的 toJSON 函数来实现的:

Date.prototype.toJSON = function() {
  return moment(this, moment.ISO_8601 ).format();
};
Run Code Online (Sandbox Code Playgroud)

我也在使用 moment.js。希望能帮助到你。