javascript - 在获得角度 5 的结果后,如何确保 typescript 接口属性为大写?
问题描述
我有一个返回以下结果的 web api
{
"customerContactID": 1,
"customerID": 1,
"firstName": "james",
"lastName": "smithman",
"primaryEmail": "james@gmail.comm",
"primaryPhone": "8788494677",
"isPrimaryContact": true
}
我有一个 Angular 5 应用程序,将接口定义为
interface CustomerContact {
CustomerContactID: number;
CustomerID: number;
FirstName: string;
LastName: string;
PrimaryEmail: string;
PrimaryPhone: string;
IsPrimaryContact: boolean;
}
并使用返回结果
this.http.get<CustomerContact>(url).subscribe(result => {
console.log("CustomerContact obtained");
console.log(result); // prints lowercase properties
this.customerContact = result;
}, error => console.error(error));
不幸的是,当我记录结果时,我可以看到属性都被小写了,所以我不能做一些事情,比如
this.currentCustomer = result.CustomerID;
因为它导致未定义。但是,我需要能够将变量值设置为从 api 结果获得的值,特别是 result.CustomerID。打字稿不允许我这样做
this.currentCustomer = result.customerID;
因为它导致
TS2551: Property 'customerID' does not exist on type 'CustomerContact'. Did you mean 'CustomerID'?
尽管编译器 [at-loader] 错误,如何将变量的值设置为 result.customerID 的值?
我根本无法更改 API 合同,此外,我的打字稿界面必须为属性名称使用大写字母。
UPDATE 1 作为下面提到的@pArth savadiya,看起来我可以做到这一点
虽然,我不确定是否会产生影响,如果有的话
我不相信这是 Convert 返回 JSON Object Properties to (lower first) camelCase的副本, 因为该问题的结果模型具有大写属性,这不是我在这里所拥有的。
更新 2 经过仔细观察,我意识到这里的大问题是 api 响应属性大小写与 angular/typescript 大小写不匹配之间的 MISTMATCH。如果它们不一样,它会导致问题并强制使用奇怪的解决方法。解决方案只是将接口外壳与此特定请求的响应外壳相匹配。就这么简单。谢谢大家。
解决方案
在您的代码中,您将 HTTP 响应结果与您的 typescript 接口(CustomerContact)紧密耦合,而不是使用它。
this.http.get <any> (url).subscribe(result => {
console.log("CustomerContact obtained");
console.log(result); // prints lowercase properties
this.customerContact = result;
}, error => console.error(error));
然后你可以写 this.currentCustomerID = result.customerID;
或者你可以这样尝试: this.currentCustomer = result["customerID"];
推荐阅读
- azure-devops - 有没有办法将 gitignore 模板添加到 azure devops 中的新项目?
- excel - 搜索以连接列并在从另一个工作簿中选择额外数量之间,该数量应增加
- javascript - react-native-webrtc 远程流在 android 5.0.2 上不起作用
- sql - 如何提取SAS PROC SQL passthru中的记录,按日期过滤,但日期是字符串格式?
- javascript - 如何为每个 wordpress 帖子点击创建单独的弹出表单
- reactjs - 设置标题React的行数
- linux - 如何通过 ssh 将 VSC 与 Fedora 连接?
- docker - 更新 docker 上的根证书
- typescript - 汇总:从外部模块捆绑/嵌入 wasm 代码
- javascript - 由于大量 JSON 响应,AJAX 请求失败