不幸的是,重现这个问题的总代码会很广泛,所以我希望我的问题是显而易见的,我可以轻松提供。如果需要,我会发布更完整的解决方案。
首先,我定义一个接口:
export interface ITest {
myDate: Date;
}
然后我创建一个数组用于测试:
export const TEST: ITest[]=[{myDate: new Date(1995, 8, 1)}]
我使用 Angular2 中的一个服务来公开这些内容,该服务正在访问 InMemoryDbServiceangular2-in-memory-web-api
。我调用它并获取数组的代码如下:
get(): Promise<ITest[]>{
return this.http.get(this.testUrl)
.toPromise()
.then(response => response.json().data as ITest[])
.catch(this.handleError);
}
...然后我将其带入我的组件中:
this.testService.get().then(tests => {
this.tests = tests;
console.log("Date Type:"+typeof(this.tests[0].myDate));
});
这一切都很好,但问题是console.log
那里显示的语句导致:
Date Type:string
其中的数据是正确的,因为我的日期保存的字符串是1995-09-01T07:00:00.000Z
,但主要问题是 - 这不是Date
它是一个string
!在 VS Code 中,我什至获得了类似方法的代码补全toDateString
但是当我执行它们时我(当然)得到toDateString is not a function
.
我很确定问题是发生在response => response.json().data as ITest[]
,但是为什么日期数据没有被转换为实际的Date
?我做错了,我明白。我应该如何处理这个问题,以便我可以让我的对象获得我期望的类型?