在angular应用中使用API​​获取数据时添加通用的目的是什么

时间:2019-04-30 10:23:11

标签: angular typescript api

我正在测试一个有角度的应用程序,我不清楚用api获取数据。我看到了泛型(Device []),这个泛型是一个类,其属性不同于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不存在一些其他属性,并且Device.ts中的某些属性根本没有被获取。那么在获取数据时添加Device []的目的是什么

1 个答案:

答案 0 :(得分:1)

在Typescript中提供类型对实际数据没有任何作用。例如,您的情况:

this.http.post<Device[]>('/api/getEntitlements', this.filter)

当您将post方法赋予类型Device[]时,您说返回的数据将是Device[]类型的,则帖子将返回Observable,因此它将是{{1 }}。

提供类型对于编写代码,编辑器智能和调试很有帮助。

例如,当您说从API返回的数据将为Device[]类型,并且如果在您的订阅下,您执行以下操作:Device[],那么智能编辑器将显示错误,因为数组具有其中没有道具res.data

如果返回的数据和您为data指定的类型不同,则应提供适合返回数据的所有属性的适当类型。