Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.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
在angular app中使用API获取数据时添加泛型的目的是什么_Angular_Typescript_Api - Fatal编程技术网

在angular app中使用API获取数据时添加泛型的目的是什么

在angular app中使用API获取数据时添加泛型的目的是什么,angular,typescript,api,Angular,Typescript,Api,我正在测试一个angular应用程序,我不清楚api如何获取数据。我看到了generic(Device[]),这个generic类的属性与api获取的属性不同。请看下面的代码片段,我不明白这是否真的会影响api获取数据 Device.ts export class Device { DeviceId: string; type: String; idtype: String; } Actual compoenent.ts getData(){ this.http.p

我正在测试一个angular应用程序,我不清楚api如何获取数据。我看到了generic(Device[]),这个generic类的属性与api获取的属性不同。请看下面的代码片段,我不明白这是否真的会影响api获取数据

Device.ts
export class Device {
    DeviceId: string;
    type: String;
    idtype: String;
}

Actual compoenent.ts
getData(){
  this.http.post<Device[]>('/api/getEntitlements', this.filter)
   subscribe(res => {......})
}

Data fetched by API are

End Customer|Account: "jdfdbdfbh"
End Customer|AccountName: "gefege"
End Customer|UserEmail: "something@djdj.com"
End Customer|UserFirstName: "",
DeviceId:"fjhjd"
Device.ts
导出类设备{
DeviceId:字符串;
类型:字符串;
idtype:字符串;
}
实际成分
getData(){
this.http.post('/api/getrights',this.filter)
订阅(res=>{……})
}
API获取的数据是
最终客户|账户:“jdfdbdfbh”
最终客户|账户名称:“gefege”
最终客户|用户电子邮件:something@djdj.com"
最终客户| UserFirstName:“”,
设备ID:“fjhjd”

我发现还有一些附加属性Device.ts不存在,而且Device.ts中的一些属性根本没有被提取。那么,在获取数据时添加设备[]的目的是什么呢?在Typescript中输入类型与实际数据无关。例如,在您的案例中:

this.http.post<Device[]>('/api/getEntitlements', this.filter)
this.http.post('/api/getrights',this.filter)
当您将类型
Device[]
指定给post方法时,您说返回的数据将是类型
Device[]
,post将返回一个可观察的,因此它将是类型
Device[]
的可观察数据

给出类型对于编写代码、编辑器智能和调试都很有用

例如,当您说从API返回的数据将是
设备[]
类型时,如果在订阅下执行类似于:
res.data
的操作,智能编辑器将显示错误,因为数组中没有prop
数据


如果返回的数据和您为
post
提供的类型不同,那么您应该提供适合返回数据所有属性的适当类型。

@karansys如果您认为添加的答案解决了您的问题,您也可以接受答案。请参见此处的链接: