Observable Map does not cast to typescript class

烈酒焚心 提交于 2019-12-23 03:50:23

问题


I am using angular 2 and I am trying to call an endpoint to return a collection of objects.

I have the following TypesScript class

export class Route
{
    public branchId: number;
    public branch: string;
    public isTest: boolean = true;
}

I have a api endpoint which returns the following Json

[{"id":610,"branch":"Coventry"},{"id":620,"branch":"Shoreham"}]

I have a route service which calls the endpoint using the following code

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));
}

It appears that the response.json() is not being cast to data type Route. Why is this?


回答1:


You cannot do a strict cast like that in TypeScript and have the objects become that type. The cast is simply a transpiler trick to tell the rest of your code that you are working with a Route array. To truly get the json data to be of type Route and not just Object you can use the assign method to type them like so:

const routes: Route[] = (response.json() as []).map((obj) => {
     return Object.assign(new Route(), obj);
}) as Route[];

If the json data does have all of the properties set then there is no need to use the assign method because at that point you are developing against an interface which should work as if you were working with the typed object.



来源:https://stackoverflow.com/questions/43737654/observable-map-does-not-cast-to-typescript-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!