Observable Map不会转换为typescript类

时间:2017-05-02 12:15:23

标签: angular rxjs

我正在使用angular 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。为什么是这样?

1 个答案:

答案 0 :(得分:3)

你不能像在TypeScript中那样进行严格的强制转换,并让对象成为那种类型。演员只是一个转换器技巧,告诉你的其余代码你正在使用Route数组。要真正使json数据的类型为Route,而不仅仅是Object,您可以使用assign方法输入它们,如下所示:

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

如果json数据确实设置了所有属性,则不需要使用assign方法,因为此时您正在开发一个接口,该接口应该像使用类型化对象一样工作