joe*_*oey 5 javascript typescript angular
我有一个返回以下结果的 web api
{
"customerContactID": 1,
"customerID": 1,
"firstName": "james",
"lastName": "smithman",
"primaryEmail": "james@gmail.comm",
"primaryPhone": "8788494677",
"isPrimaryContact": true
}
Run Code Online (Sandbox Code Playgroud)
我有一个 angular 5 应用程序,它定义了一个接口
interface CustomerContact {
CustomerContactID: number;
CustomerID: number;
FirstName: string;
LastName: string;
PrimaryEmail: string;
PrimaryPhone: string;
IsPrimaryContact: boolean;
}
Run Code Online (Sandbox Code Playgroud)
并使用返回结果
this.http.get<CustomerContact>(url).subscribe(result => {
console.log("CustomerContact obtained");
console.log(result); // prints lowercase properties
this.customerContact = result;
}, error => console.error(error));
Run Code Online (Sandbox Code Playgroud)
不幸的是,当我记录结果时,我可以看到属性都被小写了,所以我不能做这样的事情
this.currentCustomer = result.CustomerID;
Run Code Online (Sandbox Code Playgroud)
因为它导致未定义。但是,我需要能够将变量值设置为从 api 结果获得的值,特别是 result.CustomerID。打字稿不允许我做
this.currentCustomer = result.customerID;
Run Code Online (Sandbox Code Playgroud)
因为它导致
TS2551: Property 'customerID' does not exist on type 'CustomerContact'. Did you mean 'CustomerID'?
Run Code Online (Sandbox Code Playgroud)
尽管编译器 [at-loader] 出错,如何将变量的值设置为 result.customerID 的值?
我根本无法更改 API 合同,而且,我的打字稿接口必须对属性名称使用大写。
UPDATE 1
as @pArth savadiya 在下面提到,看起来我可以做到这一点

虽然,我不确定是否有影响,如果有的话
我不相信这是Convert返回的 JSON Object Properties to (lower first) camelCase的副本, 因为该问题有一个具有大写属性的结果模型,这不是我在这里所拥有的。
更新 2 经过仔细观察,我意识到这里的大问题是 api 响应属性大小写和 angular/typescript 大小写不匹配之间的 MISTMATCH。如果它们不相同,则会导致问题并强制执行奇怪的解决方法。解决方案只是将接口外壳与此特定请求的响应外壳相匹配。就这么简单。谢谢大家。
Pad*_*han -4
在你的界面改变
CustomerID: number;
Run Code Online (Sandbox Code Playgroud)
到
customerID: number;
Run Code Online (Sandbox Code Playgroud)
它将按您的预期工作。
| 归档时间: |
|
| 查看次数: |
5369 次 |
| 最近记录: |