繁体   English   中英

在订阅函数中使用Moment.js解析JSON数组

[英]Parse a JSON array with Moment.js in a subscribe-function

我在data JSON数组中有多个time项,我想用Moment.js对其进行解析和格式化,然后将它们存储到this.appointmentTimes数组中,可以使用{{appointmentTime.time}}在视图中轻松访问该数组。

这是我的JSON:

[
  { "time":"2018-10-22T14:30:00+0200", "slotsAvailable":1 },
  { "time":"2018-10-22T14:45:00+0200", "slotsAvailable":1 },
  { "time":"2018-10-22T15:00:00+0200", "slotsAvailable":1 }
]

页面刷新后,出现此错误:

ERROR in src/app/pages/booking/form/booking.component.ts(75,9): error TS2322: Type 'string' is not assignable to type 'object[]'.
src/app/pages/booking/form/booking.component.ts(76,22): error TS2345: Argument of type 'object[]' is not assignable to parameter of type 'string'.

这是我的相应功能,将通过我的视图执行。

private appointmentLocations: Array<object> = [];
private appointmentTypes: Array<object> = [];
private appointmentTimes: Array<object> = [];

onChangeTypeId(TypeId) {
    console.log(TypeId);
    this.selectedAppointmentTypeId = TypeId;
    this.apiService
      .getAppointmentTimesById(
        this.selectedAppointmentTypeId,
        this.selectedAppointmentLocation,
        this.selectedDatePicker
      )
      .subscribe((data: Array<object>) => {
        /*this.appointmentTimes = data; */
        this.appointmentTimes = JSON.stringify(
          JSON.parse(data).map(function(data) {
            var pattern = 'HH:mm';
            data = moment(data.time).format(pattern);
            return data;
          })
        );
        console.log(data);
      });
  }
}

订阅之前的.map(response => response.json()) ,因为响应是字符串,而不是JSON。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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