I am using Angular 4's new HttpModule to retrieve data from a REST-Service. The problem is, that the data contains a Date typed property. I've seen this thread but when I try the solution suggested in the thread, I get the following error: res.json is not a function
Here is my code:
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 || {};
}
And here is the data from the service:
[
{
"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": [
]
}
]
You are probably using the new HttpClientModule, rather then the old HttpModule. With HttpClient, the deserialization from JSON is done automatically, so there is no response.json() method.
More about it in angular docs: https://angular.io/guide/http
Also note then with HttpClient, you can specify interface of the response, so it will automatically map it for you:
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;
});
This should work also with Date type i guess.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With