4

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.

SebastianG
  • 8,563
  • 8
  • 47
  • 111

1 Answers1

2

You can use format before sending to backend.

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

What I normally do is

momentDate.utc().toISOString()
Icycool
  • 7,099
  • 1
  • 25
  • 33
  • I thought about that, but the issue is my form is reusable and some controls might be/ might not be in the form group. If I have to rebuild the whole object from scratch, I'll have to put in logic around the flexibility of it and hack my way around it, I was wondering if anything else is possible first – SebastianG Jul 10 '19 at 09:22
  • @MichaelB For me the form resides in component, and the formatting is done in service before sending http, or inside model constructor. If you really want to get a string as form value, you can write your own custom adapter as well. – Icycool Jul 10 '19 at 15:38