Parse date with Angular 4.3 HttpClient

Viewed 34210

I'm currently switching to the new HttpClient of Angular 4.3. One advantage is that I can specify a type info on the GET method and that the returned JSON is parsed into the given type, e.g.

this.http.get<Person> (url).subscribe(...)

But unfortunately, all dates in the JSON are parsed as numbers in the resulting object (probably because the Java Date objects are serialized as numbers in the backend).

With the old Http I used a reviver function when calling JSON.parse() like this:

this.http.get(url)
  .map(response => JSON.parse(response.text(), this.reviver))

and in the reviver function I created date objects from the numbers:

reviver (key, value): any {
  if (value !== null && (key === 'created' || key === 'modified'))
    return new Date(value);

  return value;
}

Is there a similar mechanism with the new HttpClient? Or what is the best practice to do conversion when the JSON is parsed?

5 Answers

Similar to Jonas Stensved's answer, but using pipes:

import { map } from "rxjs/operators";

this.http.get(url)
  .pipe(
    map(response => {
      response.mydate = new Date(response.mydate);
      return response;
    })

Note the different import syntax of the map operator.

Pipes were introduced in RxJS 5.5. They facilitate import handling, code readability, and reduce bundle size. See Understanding Operator Imports.

You still can, but you need to import the map()-operator from rxjs like this:

import 'rxjs/add/operator/map';

Then you can, just as Diego pointed out, use the map like this:

return this.http.get<BlogPost>(url)
.map(x => {
x.published = new Date(String(x.published));
    return x;
})
[...]

You can use:

this.http.get(url, { responseType: 'text' })
    .map(r => JSON.parse(r, this.reviver))
    .subscribe(...)

Update for rxjs 6+

this.http.get(url, { responseType: 'text' })
    .pipe(map(r => JSON.parse(r, this.reviver)))
    .subscribe(...)
Related