[英]Observable Map does not cast to typescript class
我正在使用角度2,並且嘗試調用端點以返回對象集合。
我有以下TypesScript類
export class Route
{
public branchId: number;
public branch: string;
public isTest: boolean = true;
}
我有一個api端點,它返回以下Json
[{"id":610,"branch":"Coventry"},{"id":620,"branch":"Shoreham"}]
我有一個使用以下代碼調用端點的路由服務
public getRoutes(): Observable<Route[]>
{
const url = 'http://localhost/routes';
return this.http.get(url)
.map((response: Response) =>
{
const routes: Route[] = response.json() as Route[];
if (routes.length > 0) {
console.log(routes[0].isTest);
//This returns undefined I was expecting the boolean value true
}
return routes;
}
)
.catch(e => this.httpErrorService.handleError(e));
}
似乎沒有將response.json()強制轉換為數據類型Route。 為什么是這樣?
您不能像在TypeScript中那樣進行嚴格的轉換,而讓對象成為該類型。 強制轉換只是一個轉譯技巧,可以告訴其余代碼您正在使用Route
數組。 要真正使json數據具有Route
類型,而不僅僅是Object
類型,可以使用assign
方法鍵入它們,如下所示:
const routes: Route[] = (response.json() as []).map((obj) => {
return Object.assign(new Route(), obj);
}) as Route[];
如果json數據確實設置了所有屬性,則無需使用assign
方法,因為此時您正在針對接口進行開發,該接口應該像處理類型對象一樣工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.