【问题标题】:Convert class attributes to UpperCamelCase将类属性转换为 UpperCamelCase
【发布时间】:2021-03-26 10:19:33
【问题描述】:

我在 TypeScript 中有一个类,它的属性用 camelCase 编写。 该类的实例需要在处理 Web 服务的 http 请求正文中使用。 问题是,WebService 的后端是用 C# 编写的,它试图使用 UpperCamelCase 表示法访问属性。

在 http 请求中发送类时,如何将类的属性从 camelCase 转换为 UpperCamelCase?

例子:

class Test1:

httpClient: CustomHttpClient;

public attributeOne
public attributeTwo

constructor(att1,att2):{
this.attributeOne = att1;
this.attributeTwo = att2;
this.httpClient = new CustomHttpClient();

}

sendRequest(){
const test = new Test1();
this.httpClient.post(url, test , null);
}

WebService 将尝试像Wise 一样访问正文:

test.AttributeOne
test.AttributeTwo;

因此导致错误,因为不存在此类属性。

出于 linting 等原因,我不想将 TS 中的属性更改为 UpperCamelCase。

我如何做到这一点?

【问题讨论】:

    标签: c# typescript https data-conversion camelcasing


    【解决方案1】:

    尝试使用 HttpParams 将请求正文属性名称设置为您想要的任何内容。示例:

       const params = new HttpParams()
          .set('para1', "value1")
          .set('para2',"value2");
     
       const body=JSON.stringify(person);
    
    return this.http.post<Person>(this.baseURL + 'people', body,{'headers':headers, 'params': params})
       
    

    取自https://www.tektutorialshub.com/angular/angular-http-post-example/

    【讨论】:

      【解决方案2】:

      我成功地做到了:

      我安装了一个名为“camelcase-keys”的 npm 包 (npm install camelcase-keys)

      我将我的对象作为这样的参数传递:

      const body = camelcaseKeys(JSON.parse(JSON.stringify(companyDetails)), { deep: true, pascalCase: true });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-08
        • 2023-02-11
        • 2011-05-03
        • 1970-01-01
        • 2020-12-11
        • 2019-12-13
        • 2017-08-08
        • 1970-01-01
        相关资源
        最近更新 更多