Ecco il mio json:
{ "data": [ { "comment": "3541", "datetime": "2016-01-01" } ] }
Ecco il modello:
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) => response.json().data) }
Il problema è che dopo aver lanciato su Job[]
mi aspetto che la proprietà datetime
sia Date
ma che sia stringa. Non dovrebbe cast ad object Date? Cosa mi manca qui?
@Gunter è assolutamente corretto. L’unica cosa che vorrei aggiungere è in realtà come deserializzare l’object json mantenendo le sue proprietà date come date e non stringhe (dal post di riferimento non è così facile vedere questo approccio).
Ecco il mio tentativo:
export class Helper { public static Deserialize(data: string): any { return JSON.parse(data, Helper.ReviveDateTime); } private static ReviveDateTime(key: any, value: any): any { if (typeof value === 'string') { let a = /\/Date\((\d*)\)\//.exec(value); if (a) { return new Date(+a[1]); } } return value; } }
Puoi vedere questo approccio per esempio qui: Funzione JSON.parse nell’esempio dateReviver.
Spero che questo ti aiuti.
Non è ansible sapere per TS / JS che questo valore è una data. È una stringa e trattata come tale. Altri tipi di dati sono distinguibili, ma JSON non fornisce alcun supporto speciale per la data. Devi convertirlo manualmente.
Vedere ad esempio questa discussione su come trasportare e convertire una data usando JSON Come si formatta una data Microsoft JSON?