angular2 map data as specific object type

前端 未结 4 2020
梦如初夏
梦如初夏 2021-01-04 13:50

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          


        
4条回答
  •  青春惊慌失措
    2021-01-04 14:13

    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.

    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);
        })
    

    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:

    • How do I cast a JSON object to a typescript class

提交回复
热议问题