将类属性转换为大写字母

问题描述

我在 TypeScript 中有一个类,它具有用驼峰命名法编写的属性。 该类的实例需要在处理 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。

我如何实现这一目标?

解决方法

尝试使用 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/

,

我设法做到了明智:

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

我将对象作为参数传递,如下所示:

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