Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular2和Typescript是否需要为每个api调用声明模型_Angular_Typescript - Fatal编程技术网

Angular2和Typescript是否需要为每个api调用声明模型

Angular2和Typescript是否需要为每个api调用声明模型,angular,typescript,Angular,Typescript,来自Angular 1的背景,我曾经让我的所有模型声明为POCO,我的web api调用返回数据 datacontext.query('api/OwnerData/GetOwners').then(function (d) { vm.domain = d; } 现在使用Angular2和Typescript,我有两个选择。或者我可以使用map并获取一个JSON对象,将其分配给组件中的属性,然后在视图中使用它 this.http.get(`/api/OwnerData/

来自Angular 1的背景,我曾经让我的所有模型声明为POCO,我的web api调用返回数据

 datacontext.query('api/OwnerData/GetOwners').then(function (d) {
            vm.domain = d;
}
现在使用Angular2和Typescript,我有两个选择。或者我可以使用map并获取一个JSON对象,将其分配给组件中的属性,然后在视图中使用它

this.http.get(`/api/OwnerData/GetOwners`, { headers: this.getHeaders() })
        .map(r => r.json())
        .catch(handleError);
或者,我可以使用不同的映射函数将其映射到强类型对象。但如果我走这条路,我将不得不在后端用typescript定义整个域模型。加上一套方法来映射它们。我觉得这是一个太多的工作和重复。另一方面,如果我使用JSON,那么我将失去类型安全性


你对此有何看法。谢谢你抽出时间。(我使用的是Angular 2.4和Typescript 2.1.5)

您只需转换到与JSON完全匹配的接口即可。这样可以得到自动完成和编译错误,但不需要实现任何方法。在运行时忽略接口。因此,在运行时不会获得任何类型安全性

interface MyData {
  a:string;
  b:number;
}

创建一个服务来调用您的API。'r.json()'和'r.json()作为MyData'是相同的吗?first startement是否也对json响应进行类型转换?我很感激你回复@gunterys,两人都这么做。我不确定“first startement是否也在某种类型上对json响应进行类型转换?”这句话的意思。很抱歉,输入错误,但我得到了答案。可以肯定的是,这只是为了更方便的开发(自动完成、编译期间的类型检查),对代码执行没有任何影响。如果接收到的JSON与接口不匹配,这不会在运行时导致错误。那么最好使用构造函数创建类作为接口,该构造函数解析JSON并将其值分配给字段。
this.http.get(`/api/OwnerData/GetOwners`, { headers: this.getHeaders() })
    .map(r => r.json() as MyData)
    .catch(handleError);