angular2 地图数据作为特定对象类型 [英] angular2 map data as specific object type

查看:11
本文介绍了angular2 地图数据作为特定对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基于 Angular2 教程创建了一个非常简单的应用程序.

I created a very simple app based on the Angular2 tutorial.

首先,我有一个非常简单的书籍"模型:

To start, I have a very simple "Book" model:

 /**
 * book model
 */
export class Book {
    public data;

    /**
     * constructor
     * @param id
     * @param title
     * @param pages
     */
    constructor(
        public id,
        public title:string,
        public pages:Array
    ){
        alert('it works'); // just a check
    }
}

在我的服务中,我得到了一本书:

In my service, I get a book like this:

return this._http.get('getBook/1')
        .map(function(res){
            return <Book> res.json();
        })

我的期望是这将获得生成的 JSON 数据并将其映射"到 Book 对象.

My expectation was that this would get the resulting JSON data and "map" it to a Book object.

然而,它只返回一个类型为Object"的对象.

However, it just returns an object with type "Object".

我可以自己创建一个新的 Book 对象并在构造函数中传递参数,如下所示:

I could create a new Book object myself and pass the parameters in the constructor, like this:

return new Book(res.id, res.title, res.pages);

这是最好的方法吗?我错过了什么吗?

Is this the best way to do this? Did I miss something?

推荐答案

是的,将对象转换为 TypeScript 中的类型不会创建此类型的实例.它只是 TypeScript 用于类型检查的工具.

Yes, casting an object to a type in TypeScript doesn't create an instance of this type. It's just a facility of TypeScript for type checking.

如果你真的想要一个 Book 的实例,你需要使用类似的东西:

If you want actually an instance of Book you need to use something like that:

return this._http.get('getBook/1')
    .map(function(res){
        var data = res.json();
        return new Book(data.id, data.title, data.pages);
    })

回答您的问题.事实上,如果您的类型中只有字段(例如带有接口),则强制转换就足够了.此外,如果您有稍后要使用的方法,则有必要隐式创建 Book 类型的实例(见上文)而不是强制转换.否则您将无法使用它们(它们将在您的对象上未定义)...

To answer your question. In fact if you only have fields into your type (with an interface for example), casting is enough. Moreover if you have methods you want to use later, it's necessary to implicitly create an instance of the Book type (see above) instead of casting. Otherwise you won't be able to use them (they will be undefined on your object)...

查看此问题了解更多详情:

See this question for more details:

这篇关于angular2 地图数据作为特定对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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