How do I convert the result of an HTTP request from JSON format to an object in TypeScript?
Below is the code snippet:
Component:
import { Component } from '@angular/core';
import { DateTimeService } from './datetime.service';
import { DateTime } from './datetime'
@Component({
selector: 'my-app',
moduleId: module.id,
templateUrl: 'app.component.html',
providers: [DateTimeService]
})
export class AppComponent {
constructor(private _dateTimeService: DateTimeService){ }
dateTime: DateTime = new DateTime();
getDateTime() {
this._dateTimeService.getDateTime().subscribe(data => this.dateTime = data,
error => alert("error"),
() => alert("done"));
debugger;
alert(this.dateTime.date);
alert(this.dateTime.milliseconds_since_epoch);
alert(this.dateTime.time);
}
}
Service:
import { Http } from '@angular/http';
import {Injectable} from'@angular/core';
import 'rxjs/add/operator/map'
import { DateTime } from './datetime'
@Injectable()
export class DateTimeService{
constructor(private _http: Http) { }
getDateTime() {
return this._http.get('http://date.jsontest.com').map(res => <DateTime>res.json());
}
}
Upon running the code, all properties of the DateTime
object are undefined. However, if I do not cast the incoming data to be of type DateTime
in my service and use JSON.stringify(data.time)
instead, I am only able to access a single property.