我想将前端通过API获得的Date对象显示为“ shortTime”,因此只显示小时和分钟。
但是当我通过以下方式做到这一点
<h2>{{data.scheduleTime | date:'shortTime'}} - {{data.actualLandingTime | date:'shortTime'}}</h2><br>
我收到以下错误: InvalidPipeArgument:“无法将“ 03:45:00”转换为日期”用于管道“ DatePipe”
我认为那是因为Angular认为对象的类型不是Date ...
我通过JSON格式的API调用接收这些对象。我制作了一个模型来设置对象的类型。 “ scheduleTime”和“ actualLandingTime”都是模型中的日期对象:
我的模型调用FlightInfoModel:
actualLandingTime: Date;
scheduleTime: Date;
我收到它们的方式是:
actualLandingTime: "2020-04-29T03:17:33.000+02:00"
scheduleTime: "03:45:00"
对于我两者来说,我只想显示小时和分钟。
如果有助于发现问题,这就是我如何获取该页面的API:
data: FlightInfoModel;
ngOnInit(): void {
this.flightService.getFligthInfo<any>('129392719696922308').subscribe(response => {this.data = response, console.log(response)},
error => console.log(error));
}
答案 0 :(得分:0)
您为scheduleTime接收的数据不是有效的日期格式,因为它仅包含时间。一个有点棘手的解决方案是从获取的字符串中创建一个具有任意年,月,日和时间的新Date对象。
let scheduleDate = new Date(2020, 4, 4, ...scheduleTime.split(':').map(t => Number(t));
这会将时间字符串的时,分和秒传递到Date构造函数中。
您可以在映射步骤中执行类似于上述代码的操作(即,将可观察到的响应传递给rxjs映射运算符)。您可能还想将scheduleTime的类型更改为Date | string
,并在它是字符串而不是日期的实例时进行转换。
这是完整的代码示例:
this.flightService.getFligthInfo<any>('129392719696922308').pipe(
map(info => {
if(typeof info.scheduleTime === "string") {
const splitTime: number[] = (<string>info.scheduleTime)
.split(':')
.map(t => Number(t));
return {
actualLandingTime: info.actualLandingTime,
scheduleTime: new Date(2020, 4, 4, ...splitTime)
}
}
return info
}
)
别忘了从rxjs/operators
导入地图
当您将其通过日期管道传递时,它将接受为有效日期。