【问题标题】:angular2 & typescript & reactiveX : how to cast http get resultangular2 & typescript & reactiveX:如何转换 http 获取结果
【发布时间】:2016-10-19 16:56:00
【问题描述】:

假设我们在这个 url /api/stuffs/ 有一个 rest api,我们可以在其中获取 Stuff 的列表。

这里是http获取Stuff列表的代码:

getStuffs(): Observable<Stuff[]> {
    return this.http.get(this.url)
        .map(this.extractStuffs)
        .catch(this.handleError);
}

private extractStuffs(res: Response) {

    let stuffs = res.json() as Stuff[];

    return stuffs || new Array<Stuff>();
}

这段代码一切正常,除了extractStuffs函数中的stuffs数组不是Stuff的数组而是Object的数组,即使函数的签名是Observable&lt;Stuff[]&gt; 并且来自 api 的结果被转换为 Stuff[]。奇怪的是 typescript 编译器没有抛出任何错误(即使结果类型与签名不同),如果我们查看生成的 JS 文件,这是完全正常的:

StuffService.prototype.extractStuffs = function (res) {
    var stuffs = res.json();
    return stuffs || new Array();
};

显然编译器甚至没有考虑将结果转换为Stuff[]

有什么方法可以在不手动进行的情况下正确投射?

谢谢。

【问题讨论】:

    标签: angular typescript casting frontend reactivex


    【解决方案1】:

    每当我遇到类似情况时,我都会通过一个循环进行投射(我猜你是手动定义的)。

    这是一个客户而不是东西的例子

    getCustomers(code: string) {
            let url = environment.baseServicesUrl + 'customer';
            let jsonParam = {code: code};
            return this.http.post(url, jsonParam, this.getOptions())
                        .map(this.extractData)
                        .map((customerJsons) => {
                            let customers = new Array<Customer>();
                            customerJsons.forEach((customerJson) => {
                                customers.push(<Customer>customerJson);
                            })
                            return customers
                        })
                        .catch(this.handleError);
        }
    

    铸造类型 Customer 是一个接口。

    这是Customer.interface.ts

    的代码
    import {Relationship} from './relationship.interface';
    
    export interface Customer {
        customerId: string;
        name: string;
        lastName: string;
        code: string;
        relationships: Array<Relationship>;
    }
    

    这是 Relationship.interface.ts

    的代码
    export interface Relationship {
        id: string;
        type: string;
    }
    

    【讨论】:

    • 省略了说单个对象转换也不起作用,&lt;Stuff&gt;stuffJson 仍然返回Object 而不是Stuff。这是生成的 js => jsonStuffs.forEach(function (jsonStuff) { return stuffs.push(jsonStuff); }); 我的编译器中可能缺少什么吗???
    • 我猜,Stuff 必须是一个接口(而不是一个类)才能进行强制转换。你是这种情况吗?
    • 确实是一门课。用接口重试。
    • 界面变化不大
    • 也许值得补充一点,Typescript 中的接口没有编译到运行时代码中。它们对于在开发时强制键入很有用。见 (stackoverflow.com/questions/22875636/…)
    猜你喜欢
    • 2016-10-14
    • 2016-12-14
    • 2017-09-09
    • 1970-01-01
    • 2016-03-30
    • 2016-11-28
    • 1970-01-01
    • 2016-04-03
    • 2018-01-19
    相关资源
    最近更新 更多