我正在尝试像这样显示数据:
<a *ngFor="let month of months">
<div>
<h4>{{month.name + month.date.getFullYear()}}</h4>
<p *ngFor="let topic of month.topics">
<span>{{topic.description}}</span>
<li *ngFor="let item of topic.items">
<span>{{item.content}}</span>
</li>
</p>
</div>
</a>
当我像这样使用静态 Month[] 数据时,这非常有效:
export const MONTHS: Month[] = [
{ id: 0, name: "September ", date: new Date(2020, 9), topics:[{id: 0, description: "I need a new description", items: [{ id: 0, content: "I need a new todo", isDone: false}]}]},
{ id: 1, name: "August ", date: new Date(2020, 8), topics:[{id: 0, description: "I need a second description", items: [{ id: 0, content: "I need a second todo", isDone: false}]}]},
];
但是,当我尝试从内存服务器中获取 Month[] 时,如下所示:
///The database
export class InMemoryDataService implements InMemoryDbService {
createDb() {
const months = [
{ id: 0, name: "September ", date: new Date(2020, 9), topics:[{id: 0, description: "I need a new description", items: [{ id: 0, content: "I need a new todo", isDone: false}]}]},
{ id: 1, name: "August ", date: new Date(2020, 8), topics:[{id: 0, description: "I need a second description", items: [{ id: 0, content: "I need a second todo", isDone: false}]}]},
];
return {months};
}
}
///The month.service
/** GET months from the server */
getMonths(): Observable<Month[]> {
return this.http.get<Month[]>(this.monthsUrl)
.pipe(
tap(_ => this.log('fetched months')),
catchError(this.handleError<Month[]>('getMonths', []))
);
}
///the .ts component of the html display
export class CurrentMonthComponent implements OnInit {
months: Month[];
constructor(private monthService: MonthService) { }
ngOnInit(): void {
this.getMonths();
}
getMonths(): void {
this.monthService.getMonths()
.subscribe(months => this.months = months);
}
}
此时 html 中的 month.date.getFullYear() 行会引发此异常:
core.js:4197 ERROR TypeError: month_r1.date.getFullYear is not a function
at CurrentMonthComponent_a_3_Template (current-month.component.html:6)
为什么从服务器检索 date 时不再理解 date 是 Date 对象?getMonths() 方法不应该返回一个将日期定义为日期的 Month[] 吗?还是与 rxjs-observables 有关?这是我的month.ts界面供参考。谢谢!
export interface Month {
id: number;
name: string;
date: Date;
topics: Array<Topic>;
}