How to get Date object from json Response in typescript

Viewed 46652

Here is my json:

{
  "data": [
    {
      "comment": "3541",
      "datetime": "2016-01-01"
    }
  ]
}

Here is model:

export class Job {
    constructor(comment:string, datetime:Date) {
        this.comment = comment;
        this.datetime = datetime;
    }

    comment:string;
    datetime:Date;
}

Query:

getJobs() {
        return this._http.get(jobsUrl)
            .map((response:Response) => <Job[]>response.json().data)
}

Problem is that after casting to Job[] i expect datetimeproperty to be Date but it is string. Shouldn't it cast to Date object? What am i missing here?

4 Answers

If usage of custom TypeScript transformer is possible, ts-transformer-dates could be used:

import { toDates } from 'ts-transformer-dates';

const value = {
  "data": [
    {
      "comment": "3541",
      "datetime": "2016-01-01"
    }
  ]
};

export class Job {
    constructor(comment:string, datetime:Date) {
        this.comment = comment;
        this.datetime = datetime;
    }

    comment:string;
    datetime:Date;
}

console.log(toDates<{data:Job[]}>(value));

Output:

{ data: [ { comment: '3541', datetime: 2016-01-01T00:00:00.000Z } ] }

You can achieve it using 2 properties: a string property (say dateStr) for passing the date and a Date property (say dateVal) to hold the data object after conversion.

Then in your constructor, you can simply do something like dateVal = new Date(dateStr).

Related