简体   繁体   中英

Observable Map does not cast to typescript class

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM