我在Angular组件中创建了自己的自定义getDate()方法
getDate(date: Date){
return date.format("dd-MMMM-yyyy HH:mm").toString();
}
我从数据库中获取字符串JSON数据。这个JSON就是这样
`
"{"field":"date","oldValue":"Mon Mar 25 00:00:00 GMT 2019","newValue":"Tue Mar 26 00:00:00 GMT 2019"}, {"field":"techniqueType","oldValue":"Intra","newValue":"Intralesional"}
`
我的getList方法看起来像
getList(patientId?: number, pageNo?: number) {
const auditTrailSubscription =
this._auditTrailService.getAuditTrailUrl(patientId, pageNo,
GridConfig.ITEMS_PER_PAGE)
.subscribe(
result => {
try {
this.results = [];
this.totalItems = result.recordsCount;
this.auditTrailList = result.lstRecords;
this.auditTrailList.forEach(x => {
let jschanges = JSON.parse(`[${x.jsonChanges}]`);
jschanges.forEach(z => {
this.results.push({
userName: x.userName,
timestamp: x.timestamp,
entityName: x.entityName,
field: z.field,
oldValue: z.oldValue instanceof Date ?
this.getDate(z.oldValue) : z.oldValue,
newValue: z.newValue instanceof Date ?
this.getDate(z.newValue) : z.newValue
});
});
});
} catch (e) {
console.log(e);
}
},
err => {
this.handleError(err);
}
);
this.addSubscription("auditTrail", auditTrailSubscription);
}
HTML文件
<tr *ngFor="let at of results | paginate: { itemsPerPage:
_ITEMS_PER_PAGE, currentPage: crtPage, totalItems: totalItems }"
[attr.data-row-id]="at.userId">
<td>{{ at.userName }}</td>
<td>{{ at.timestamp ? (at.timestamp | date:
AUDIT_TRAIL_DATE_TIME_FORMAT ) : 'Unknown' }}</td>
<td>{{ at.entityName }}</td>
<td>{{ at.field | titlecase }}</td>
<td>{{ at.oldValue }}</td>
<td>{{ at.newValue }}</td>
</tr>
因此,我需要使用自定义的getDate()方法并检查oldValue和newValue是否为Date类型,然后使用getDate()定制方法,否则仅返回其他值。
答案 0 :(得分:0)
使用Date.parse()
。将您的日期字符串传递到Date.parse()
中,如果它返回数字,则日期字符串为有效日期。像这样:-
if(isNaN(Date.parse("Tue Mar 26 00:00:00 GMT 2019"))){
console.log("Invalid Date");
}
else {
console.log("Valid Date")
}
或
var isDateValue = (new Date(date) !== "Invalid Date") && !isNaN(new Date(date));
让我知道它是否对您有用。
答案 1 :(得分:0)
如果AuditTrailService使用Angular的HttpClient,则可以为JSON HTTP响应提供接口。 大概是这样的:
interface AuditTrailResponse {
recordsCount: number;
lstRecords: AuditTrailRecord[];
}
在您的AuditTrailService中使用以下表示法:
this.httpClient.get<AuditTrailResponse>('the/url/of/your/endpoint', { your: params })
这样,result
将是AuditTrailResponse
而不是any
。
我不完全理解将您插入的字符串解析为JSON的行,并且AFAIK JSON.parse()
不会产生Date对象,因此您的oldValue instanceof Date
检查下面几行永远是不正确的。
但是您可以提供界面:
interface JSChange {
userName: string;
timestamp: number;
entityName: string;
oldValue: string | Date;
newValue: string | Date;
}
,如果您确实确定z
参数符合该接口,请对该接口执行强制转换。