0

我正在尝试像这样显示数据:

    <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>;
}
4

2 回答 2

1

我认为 date 属性只是 Date 的一种类型,不是实际的Date对象。

在将日期分配给this.months数组时,您需要将 BE 响应转换为实际的Date对象,然后您的代码将起作用

或者

<h4>{{month.name + (new Date(month.date)).getFullYear()}}</h4>
于 2020-08-05T18:36:52.833 回答
0

感谢您的帮助,它为我指明了正确的方向,即我的日期没有被保存为Date,而是一个必须转换回Date的字符串。

最终起作用并允许我在该 h4 标记中调用 getFullYear() 的方法是将此映射添加到我的 http get 方法中的 .pipe()

map(months => months.map(month => ({...month, date: new Date(month.date)}))),

这将它改回了一个我能够调用 getFullYear()的Date对象。

于 2020-08-08T15:09:23.977 回答