0

I have a class Person with a date field in it:

export class Persoon {
   name: string;
   dateOfBirth: Date;
}

My Java server gives a json string like:

{"person":{"name":"Jansen","dateOfBirth":"1959-04-16"}}

In the debugger I get the impression that AngularJS2 thinks it's a string, when I use a datepipe the following error occurs:

EXCEPTION: Invalid argument '1959-04-16' for pipe 'DatePipe' in [{{person.dateOfBirth | date:"dd-MM-yy"}} in PersonenComponent@26:10]

How can I make a Date of dateOfBirth?

Jaap D
  • 501
  • 5
  • 18

1 Answers1

3

You need to map the string field to a date one:

getList() : Observable<SomeModel[]> {
  return this._http.get(this._getListUrl).map(data => {
    return this.extractData(data);
  });
}

// parse a date in yyyy-mm-dd format
function parseDate(input) {
  var parts = input.split('-');
  return new Date(parts[0], parts[1]-1, parts[2]); // Note: months are 0-based
}

private extractData(res: Response) {
  var data = res.json().data || [];
  data.forEach((d) => {
    d.dateOfBirth = this.parseDate(d.dateOfBirth);
  });
  return data;
}

See this question:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Why do I get an error on this line: var data = res.json().data || []; when I try to use this code? "Property data does not exist on type Promise" – Aaron Jan 03 '18 at 15:25