【发布时间】:2018-08-09 04:45:45
【问题描述】:
我在 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
我可以预先转换它,但是使用类型的目的是什么?
这与我的类没有完全实例化有关吗?
谢谢
【问题讨论】:
-
Season实例在哪里创建? -
您没有发布相关代码,这是创建Season实例并设置其Start属性值的代码。请记住,在运行时,不再有 TypeScript。这只是 JavaScript。 JavaScript 可以将任何东西赋给任何变量。
-
好的,这就是问题所在。我假设 this.selectedSeason = season 足以确保属性保持我在类中声明的类型。那么每次我选择一个新的“季节”时,我都必须实际创建一个对象(使用新的?)?
-
没有。您必须确保季节传递给 seleccionarTemporada,这应该是一个季节,确实是一个季节。修复错误,不要绕过它。但是由于您不会告诉我们这个对象是在哪里以及如何创建和填充的,所以我们无法告诉您如何最好地修复代码。
-
道歉。我已经用完整的代码更新了帖子。
标签: angular typescript primeng