我在typeScript中有一个模型类:
export class Season {
ID: number;
Start: Date;
}
这是我的组件:
export class SeasonsComponent{
seasons: Season[];
selectedSeason: Season;
constructor(
private configService: ConfigService,
private notificationsService: NotificationsService,
) { }
ngOnInit(): void {
this.selectedSeason = new Season();
this.getSeasons();
}
getSeasons(): void {
this.configService.getSeasons().subscribe(
response => {
this.seasons= response.Data;
// Data: { Id: 1, Start: '2018-01-01T00:00:00' }
},
error => {
this.notificationsService.show("error", error.error.error, error.error.error_description);
}
);
}
selectSeason(season: Season): void {
this.selectedSeason = season;
}
}
模板:
<p-dataList [value]="seasons">
<ng-template let-season pTemplate="item">
<div class="ui-g ui-fluid text-capitalize item-list" (click)="selectSeason(season)"
[class.selected]="season === selectedSeason">
<div class="ui-md-3 text-center">
<div class="pt-4"><h5>{{ season.ID }}</h5></div>
</div>
<div class="ui-g-12 ui-md-9">
<div class="ui-g">
<div class="ui-g-2 ui-sm-6">Start: </div>
<div class="ui-g-10 ui-sm-6">{{ season.Start | date: 'MMM d' }}</div>
</div>
</div>
</div>
</ng-template>
</p-dataList>
<form class="bg-white p-4" *ngIf="selectedSeason">
<div class="row">
<div class="form-group col">
<label>Start</label>
<p-calendar name="startDate" [required]="true"
[ngModel]="selectedSeason?.Start"
[inline]="true"
[style]="{'max-width': '85%'}">
</p-calendar>
</div>
</div>
</form>
显然,Start属性的值是一个字符串,这导致我遇到一个需要Date对象的组件的问题,因为它是ngModel。
如果我添加这一行:
this.selectedSeason.Start = new Date(this.selectedSeason.Start);
我明白了:
console.log(typeof this.selectedSeason.Start); // object
我可以事先投出它但是那么使用类型的目的是什么?
这是否与我的课程没有完全实例化或某事有关?
由于
答案 0 :(得分:1)
我喜欢该服务返回转换的数据,因此您的服务可以像
getSeasons()
{
this.httpClient.get(...).map(result=>{
//Not return the result, instead return result.Data
//Moreover, we change all the result.Data to return in Start, a Date Object
return result.Data.map(d=>{
Id:d.Id,
Start:New Date(d.Start)
}
}
}
然后您的组件订阅就像
this.configService.getSeasons().subscribe(
response => {
this.seasons= response; //<--just response
},
error => {
this.notificationsService.show("error", error.error.error, error.error.error_description);
}
);