![](/img/trans.png)
[英]Typescript casting json to object in angular using `as` doesn't work
[英]Angular: Typescript casting JSON response as object model not working
我在嘗試將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);
});
很難解釋:
Date
是一個類 ,這意味着需要通過構造函數調用來創建Date類型的值。 換句話說,使用new Date(...)
創建一個類實例。
Response.json方法將僅返回JSON格式的對象,並且該類不包含任何類的實例,僅包含key:property的映射。
因此,您需要做的是將.json()返回的值手動轉換為Base對象。 可以按照以下步驟進行:
public getSingle = (keys: any[]): Observable<Badge> => {
return this._http.get(this.actionUrl + this.getKeysUrl(keys))
.map(r => r.json())
.map(v => <Badge>{
badgeNumber: v.badgeNumber,
authorizationLevel: v.authorizationLevel,
endOfValidity: new Date(v.endOfValidity)
// preferably this string should be in ISO-8601 format
})
//the mapping step can be done in other ways most likely
.catch(this.handleError);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.