【发布时间】:2018-02-11 19:54:12
【问题描述】:
我在尝试将 json 响应投射到对象时遇到问题,我的对象的所有属性都是字符串,这正常吗?
这是我的 ajax 请求:
public getSingle = (keys: any[]): Observable<Badge> => {
return this._http.get(this.actionUrl + this.getKeysUrl(keys))
.map((response: Response) => response.json() as Badge )
.catch(this.handleError);
}
这是我的徽章模型:
export interface Badge {
badgeNumber: number;
authorizationLevel: number;
endOfValidity: Date;
}
这是我调用服务功能的地方,我遇到了问题:
this._badgeService.getSingle(this.ids).subscribe(
(badge: Badge) => {
console.log(typeof(badge.endOfValidity)); // <-- returning string and not Date
},
error => console.log(error);
});
【问题讨论】:
-
as Badge是一个assertion,它实际上并没有投射任何东西。您需要自己根据 JSON 数据创建一个新的 Badge 对象。 -
我明白了,你介意告诉我上面的最佳方法吗?
标签: json angular typescript casting angular2-http