Как сохранить результат HTTP-запроса из формата JSON для объекта в TypeScript.Как сохранить извлеченный JSON как объект?
Вот мой код:
Компонент:
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);
}
}
Услуги:
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());
}
}
Все свойства DateTime
объекта не определены, когда я запускаю этот код. Однако, если я не передаю входящие данные типа DateTime
в свою службу и использую JSON.stringify(data.time)
(например), я могу получить только одно свойство.
Ваше предупреждение кажется, что это не внутри функции вы подписываетесь на. – Dylan