简体   繁体   English

可观察到的地图不会转换为打字稿类

[英]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. 我正在使用角度2,并且尝试调用端点以返回对象集合。

I have the following TypesScript class 我有以下TypesScript类

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

I have a api endpoint which returns the following Json 我有一个api端点,它返回以下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. 似乎没有将response.json()强制转换为数据类型Route。 Why is this? 为什么是这样?

You cannot do a strict cast like that in TypeScript and have the objects become that type. 您不能像在TypeScript中那样进行严格的转换,而让对象成为该类型。 The cast is simply a transpiler trick to tell the rest of your code that you are working with a Route array. 强制转换只是一个转译技巧,可以告诉其余代码您正在使用Route数组。 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: 要真正使json数据具有Route类型,而不仅仅是Object类型,可以使用assign方法键入它们,如下所示:

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. 如果json数据确实设置了所有属性,则无需使用assign方法,因为此时您正在针对接口进行开发,该接口应该像处理类型对象一样工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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