Angular 2 日期反序列化 [英] Angular 2 Date deserialization
问题描述
我有一个 Angular 2 应用程序.服务是从 api 请求数据,返回结果如下:
I have an Angular 2 application. A service is requests data from an api that returns the results like the following:
{
"data":[
{"id":1,"timestamp":"2016-04-17T19:52:53.4510935+01:00","sourceDatabaseServer":"127.0.0.1","sourceDatabaseName":"Database1","targetDatabaseServer":"192.168.99.101","targetDatabaseName":"Database2"},
{"id":2,"timestamp":"2016-04-17T19:52:53.4510935+01:00","sourceDatabaseServer":"127.0.0.2","sourceDatabaseName":"Database3","targetDatabaseServer":"192.168.99.102","targetDatabaseName":"Database4"},
{"id":3,"timestamp":"2016-04-17T19:52:53.4510935+01:00","sourceDatabaseServer":"127.0.0.3","sourceDatabaseName":"Database5","targetDatabaseServer":"192.168.99.103","targetDatabaseName":"Database6"}
]
}
我的 Angular 2 服务看起来像这样(为了简洁起见,我已经削减了错误处理,因为我们在这里走的是快乐的道路):
My Angular 2 service looks like this (I've cut the error handling for brevity as we're on the happy path here):
getList() : Observable<SomeModel[]> {
return this._http.get(this._getListUrl).map(this.extractData);
}
private extractData(res: Response) {
return res.json().data || {};
}
我的组件是这样的:
results: SomeModel[];
errorMessage: string;
ngOnInit() {
this._someService.getList()
.subscribe(
results => this.results = results,
error => this.errorMessage = <any>error);
}
我的模型是这样的:
export class SomeModel {
constructor(
public id: number,
public timestamp: Date,
public sourceDatabaseServer: string,
public sourceDatabaseName: string,
public targetDatabaseServer: string,
public targetDatabaseName: string
) { }
}
一切看起来都正常,但是当我尝试使用 DatePipe 显示时间戳时,就像这样 {{item.timestamp |date:'short'}}
应用程序崩溃并显示以下错误消息:
Everything looked like it was working however when I tried to display timestamp using the DatePipe like so {{item.timestamp | date:'short'}}
the application blows up with the following error message:
Invalid argument '2016-04-17T19:40:38.2424240+01:00' for pipe 'DatePipe' in [{{result.timestamp | date:'short'}}
经过一些调查,我相信时间戳实际上并没有被转换为 Date
类型,而只是被设置了一个 string
.我猜这是因为在调用 Response.json()
时不知道 Date
类型?还是我完全错过了其他东西?是否有解决方法或解决方法?
After some investigation I believe that timestamp is not actually being converted to the Date
type but is instead just being set a string
. I'm guessing this is becuase the Date
type isn't known at the time Response.json()
is called? or am I missing something else entirely? Is there a fix or work around for this?
推荐答案
我会将字符串字段映射到日期一:
I would map the string field to a date one:
getList() : Observable<SomeModel[]> {
return this._http.get(this._getListUrl).map(this.extractData);
}
private extractData(res: Response) {
var data = res.json().data || [];
data.forEach((d) => {
d.timestamp = new Date(d.timestamp);
});
return data;
}
这篇关于Angular 2 日期反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!