Reputation: 1217
I am new to Angular and I have several doubts about what is the best way to serialize a Date property of an object added to a POST request. Given the sample class
export class MyClass{
public dateProperty: Date;
}
I have the following code in the service:
public addMyClass(myClass: MyClass): Observable<MyClass> {
return this.http.post<MyClass>(this.apiBaseUrl, myClass);
}
I have to serialize Date in the following format 'yyyy-MM-dd hh:mm'
.
I considered different ways like defining a decorator (if possible), or overriding toJson()
method, but I don't know if these are the only options or there is a better solution...
Upvotes: 7
Views: 2741
Reputation: 351
Describing the problem that I had, I was at GMT+1, for instance, and would like to save just the date, something like "2019-04-28T00:00:00 GMT+01:00", and the JSON serialization was changing the date to "2019-04-27T23:00:00.000Z". Basically sending the wrong date, I guess you are facing something similar.
I found a wait to custom serialize everything at once for the whole project before sending it to the server, and it was by overwriting the toJSON function at the data object:
Date.prototype.toJSON = function() {
return moment(this, moment.ISO_8601 ).format();
};
I'm also using moment.js. Hope it helps.
Upvotes: 8