Angular TypeScript Date.getFullYear() 从服务器返回 Observable 时不是一个函数

Angular TypeScript Date.getFullYear() not a function when returning Observable from server

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

    <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}]}]},
];

但是,当我尝试从内存服务器中获取月份[]时,如下所示:

///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)

为什么从服务器获取日期时不再理解日期是日期对象? getMonths() 方法 return 不应该是将日期定义为日期的 Month[] 吗?或者它是否与 rxjs-observables 有关?这是我的 month.ts 界面供参考。谢谢!

export interface Month {
    id: number;
    name: string;
    date: Date;
    topics: Array<Topic>;
}

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

Either 将日期分配给 this.months 数组时,您需要将 BE 响应转换为实际 Date object 那么你的代码就可以工作了

<h4>{{month.name + (new Date(month.date)).getFullYear()}}</h4>

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

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

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

这将它改回了 Date 对象,我可以调用 getFullYear() 了。