角度2.将http响应映射到具体对象实例 [英] Angular2. Map http response to concrete object instance

查看:103
本文介绍了角度2.将http响应映射到具体对象实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用于处理http响应的通用方法如下:

Сommon approach to process http response is like that:

return this._http.get(url)
           .map((res: Response) => res.json());

为您提供Observable<Object[]>,其中Object是根据json反序列化动态创建的类型. 然后您可以在*ngFor="let item of result | async"等中使用此结果...

which provides you with an Observable<Object[]> where Object is dynamically created type from json de-serialization. Then you can use this result in *ngFor="let item of result | async" etc...

我想获取一个特定的类型实例(意味着使用new运算符来调用类型的构造函数). 尝试了不同的方法来实现这样的目标:

I'd like to get a specific type instance (meaning using new operator to call the type's constructor). Tried different ways to achieve something like that:

.map((res: Response) => { let obj = res.json(); return new MyObject(obj.id, obj.name);})

但出现此错误:Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

这种方法似乎可行,但是它太复杂了,可能无效:

This way seems to work but it's way too complicated and probably not effective:

.map((res: Response) => {
    let results = <MyObject[]>[];
    let obj = res.json();
    obj.forEach(
        function (o: any) {
            results.push(new MyObject(o.id, o.name));
        }
    );
    return results;
}

谢谢!

推荐答案

.map((res: Response) => res.json().map(obj => new MyObject(obj.id, obj.name)))

这篇关于角度2.将http响应映射到具体对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆