我正在使用 Angular 4 的新 HttpModule 从 REST 服务检索数据。问题是,数据包含 Date 类型的属性。我看过this thread但是当我尝试线程中建议的解决方案时,出现以下错误:res.json is not a function
这是我的代码:
getMarkets(): Observable<Christmasmarket[]> {
let markets: Christmasmarket[];
return this.http.get(this.apiUrl).map(this.extractData);
}
private extractData(res: Response) {
let body = res.json().data;
console.log(body);
body.forEach((d) => {
d.start = new Date(d.start)
d.end = new Date(d.end);
});
return body.data || {};
}
这是来自服务的数据:
[
{
"id": 1,
"name": "mein markt1",
"start": "2017-11-14T23:00:47.838+0000",
"end": "2017-12-14T23:00:47.838+0000",
"postalCode": "1100",
"city": "wien",
"address": "test",
"rating": 4.56,
"ratingPrice": 1.2,
"numberOfRatings": 10,
"latLng": {
"latitude": 48.208982,
"longitude": 16.373213
},
"openingHours": [
{
"open": true,
"start": 600,
"end": 1200,
"dayOfWeek": 0
},
{
"open": true,
"start": 660,
"end": 1200,
"dayOfWeek": 1
},
{
"open": true,
"start": 690,
"end": 1200,
"dayOfWeek": 2
},
{
"open": true,
"start": 600,
"end": 1200,
"dayOfWeek": 3
},
{
"open": true,
"start": 600,
"end": 1200,
"dayOfWeek": 4
},
{
"open": true,
"start": 600,
"end": 1200,
"dayOfWeek": 5
},
{
"open": true,
"start": 600,
"end": 1200,
"dayOfWeek": 6
}
],
"extraordinaryOpeningHours": [
]
}
]
最佳答案
您可能正在使用新的 HttpClientModule
,而不是旧的 HttpModule
。使用 HttpClient
,JSON 的反序列化是自动完成的,因此没有 response.json()
方法。
Angular 文档中有更多相关信息:https://angular.io/guide/http
另请注意,使用 HttpClient
,您可以指定响应的接口(interface),因此它会自动为您映射:
interface ItemsResponse {
results: string[];
}
http.get<ItemsResponse>('/api/items').subscribe(data => {
// data is now an instance of type ItemsResponse, so you can do this:
this.results = data.results;
});
我猜这也适用于 Date
类型。
关于json - 来自 REST 服务的 Angular 4.4 日期反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46861775/