首页 > 解决方案 > Angular Material datepicker + moment,为后端序列化时刻对象?

问题描述

我有一个使用带有语言环境的时刻适配器的日期选择器,日期一切正常,但我无法在后端转换它们。我从表格中得到它formGroup.value

在将其发送到后端(通过 angular firebase)之前,它看起来像:

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

但在后端记录它,看起来像:

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

值是空的,当我尝试从中获取任何类型的日期时,当然会抛出 TypeErrors。

我通过@angular/firehttpCallable 函数发送它。

编辑:当前的解决方法相当老套/不受欢迎:

    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);

我需要将它改回一个时刻对象,否则他们将在所有未来的日期停止工作。

标签: javascriptangularmomentjsangular-reactive-formsangular-moment

解决方案


您可以format在发送到后端之前使用。

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

我通常做的是

momentDate.utc().toISOString()

推荐阅读