首页 > 解决方案 > 在获得角度 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。如果它们不一样,它会导致问题并强制使用奇怪的解决方法。解决方案只是将接口外壳与此特定请求的响应外壳相匹配。就这么简单。谢谢大家。

标签: javascriptangulartypescript

解决方案


在您的代码中,您将 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"];


推荐阅读