TypeScript排序JSON日期时返回时间值全为0,排序功能失效求助
解决TypeScript中JSON数据按日期排序失效的问题
我看了你的代码,发现排序失效的根源有几个关键问题,咱们一步步来解决:
问题排查
- 排序回调未使用数组元素:你的
sortbydate方法里,sort的回调函数没有接收数组中的两个对比元素(通常叫a和b),反而一直在用未赋值的this.dueDate,这导致getTime始终返回0,排序当然不会生效。 - 未正确映射日期字段:你的数据里日期字段是
datetime_device(字符串格式),但你没有把它转换成Date对象来进行时间戳计算。 - 数据赋值错误:在
getAllNotifications中,你直接把整个响应赋值给this.notif,但实际上接口返回的数组在StatusDescription字段里,需要正确提取。
解决方案
1. 修正数据获取逻辑
首先确保你正确提取接口返回的通知数组:
getAllNotifications() { this.ws.NotifGetAll().subscribe( response => { // 提取响应中的StatusDescription数组 this.notif = response.StatusDescription; } ); }
2. 修复排序函数
修改sortbydate方法,使用数组元素的datetime_device字段,并转换为Date对象计算时间戳:
private getTime(dateString: string): number { // 把日期字符串转换成Date对象,再取时间戳 const date = new Date(dateString); return date.getTime() || 0; } public sortbydate(): void { this.notif.sort((a, b) => { // 对比两个元素的datetime_device时间戳 const timeA = this.getTime(a.datetime_device); const timeB = this.getTime(b.datetime_device); console.log(timeA - timeB); // 现在能看到正确的差值了 return timeA - timeB; // 升序排序,反过来就是降序 }); }
如果你的Notifications类里已经把datetime_device定义为Date类型,那getTime可以简化为:
private getTime(date: Date): number { return date?.getTime() || 0; } public sortbydate(): void { this.notif.sort((a, b) => { return this.getTime(a.datetime_device) - this.getTime(b.datetime_device); }); }
3. 确保服务端返回的数据正确映射
在你的服务代码中,确保Notification类正确解析datetime_device:
// 假设你的Notification类定义 export class Notification { id: string; datetime_device: Date; alarmtype_id: number; alarmnumber: number; device_serial: string; constructor(data: any) { this.id = data.id; this.datetime_device = new Date(data.datetime_device); // 关键:把字符串转成Date this.alarmtype_id = data.alarmtype_id; this.alarmnumber = data.alarmnumber; this.device_serial = data.device_serial; } } // 服务端代码修正 public NotifGetAll(): Observable<Notification[]> { let headers = new Headers(); headers.append('x-access-token', this.auth.getCurrentUser().token); return this.http.get(Api.getUrl(Api.URLS.NotifGetAll), { headers: headers }) .map((response: Response) => { let res = response.json(); if (res.StatusCode === 1) { this.auth.logout(); return []; } else { // 正确实例化Notification类,转换日期 return res.StatusDescription.map(notif => new Notification(notif)); } }); }
测试验证
现在调用sortbydate方法后,你的notif数组应该会按照datetime_device字段从小到大排序(升序),如果需要降序,把return timeA - timeB改成return timeB - timeA即可。
内容的提问来源于stack exchange,提问作者user9515832
相关产品推荐
相关产品推荐

