简体   繁体   中英

Angular Material datepicker + moment, serializing the moment objects for backend?

I have a date picker using the moment adapter with the locale, all is ok with the dates but I can't get convert them on the backend. I'm getting it from the form using formGroup.value

Before sending it to the backend (via angular firebase) it looks like:

from: Moment
_d: Sat Jul 06 2019 01:00:00 GMT+0100 (British Summer Time) {}
_i: {year: 2019, month: 6, date: 6}
_isAMomentObject: true
_isUTC: true
_isValid: true
_locale: Locale {_calendar: {…}, _longDateFormat: {…}, _invalidDate: "Invalid date", ordinal: ƒ, _dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, …}
_offset: 0
_pf: {empty: false, unusedTokens: Array(0), unusedInput: Array(0), overflow: -1, charsLeftOver: 0, …}
__proto__: Object

But on the backend logging it, looks like:

from:
>        { _isAMomentObject: true,
>          _i: [Object],
>          _isUTC: true,
>          _pf: [Object],
>          _locale: [Object],
>          _d: {},
>          _isValid: true,
>          _offset: 0 },

with the values empty and of course TypeErrors are thrown when I try to get any kind of date from it.

I'm sending it via @angular/fire as a httpCallable function.

EDIT: Current workaround which is rather hacky/unpreffered:

    let oldFrom: moment.Moment = this.from.value;
    let oldTo: moment.Moment = this.to.value;
    this.ReportForm.controls.from.setValue(oldFrom.toISOString());
    this.ReportForm.controls.to.setValue(oldTo.toISOString());
    this.submitted.emit(this.ReportForm.value);
    this.ReportForm.controls.from.setValue(oldFrom);
    this.ReportForm.controls.to.setValue(oldTo);

I need to change it back to a moment object otherwsie they'll stop working for all future dates.

You can use format before sending to backend.

momentDate.format('YYYY-MM-DD')

What I normally do is

momentDate.utc().toISOString()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM