何时在TypeScript/Angular中使用接口和模型 [英] When to use Interface and Model in TypeScript / Angular

查看:66
本文介绍了何时在TypeScript/Angular中使用接口和模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近观看了带有TypeScript的Angular 2教程,但不确定何时使用接口以及何时将模型用于数据结构.

I recently watched a Tutorial on Angular 2 with TypeScript, but unsure when to use an Interface and when to use a Model for data structures.

界面示例:

export interface IProduct {
    ProductNumber: number;
    ProductName: string;
    ProductDescription: string;
}

型号示例:

export class Product {
    constructor(
        public ProductNumber: number,
        public ProductName: string,
        public ProductDescription: string
    ){}
}

我想从URL加载JSON数据并绑定到接口/模型.有时我想要一个数据对象,而另一些时候我想要保存对象的数组.

I want to load a JSON data from a URL and bind to the Interface/Model. Sometime I want a single data object, other time I want to hold an array of the object.

我应该使用哪个?为什么?

Which one should I use and why?

推荐答案

接口仅在编译时出现.这仅允许您检查接收到的预期数据是否遵循特定的结构.为此,您可以将内容投射到此界面:

Interfaces are only at compile time. This allows only you to check that the expected data received follows a particular structure. For this you can cast your content to this interface:

this.http.get('...')
    .map(res => <Product[]>res.json());

查看以下问题:

您可以对类进行类似的操作,但与类的主要区别在于它们在运行时存在(构造函数),您可以通过处理在其中定义方法.但是,在这种情况下,您需要实例化对象才能使用它们:

You can do something similar with class but the main differences with class are that they are present at runtime (constructor function) and you can define methods in them with processing. But, in this case, you need to instantiate objects to be able to use them:

this.http.get('...')
    .map(res => {
      var data = res.json();
      return data.map(d => {
        return new Product(d.productNumber,
          d.productName, d.productDescription);
      });
    });

这篇关于何时在TypeScript/Angular中使用接口和模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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