gpt4 book ai didi

Angular/Typescript 在接口(interface)中从蛇形大小写转换为驼峰大小写

转载 作者:太空狗 更新时间:2023-10-29 17:41:12 28 4
gpt4 key购买 nike

我们目前正在进行从 AngularJS 到 Angular 的大规模升级。我们遇到了一个问题,我找不到最好的解决方案来解决它。

根据 Angular/Typescript 代码标准,我们应该使用 camelCase 定义我们所有的变量、属性名称和接口(interface)。

问题是来自后端的所有数据都与 snake_case 一起使用。

因此在每次请求后,为了创建相应的界面,我们需要将键转换为驼峰式,然后当我们传递数据时,我们需要将其返回 snake_case。

我们正在使用 lodash 这样做,但是有更好的方法吗?有没有办法使用 Typescript native 实现来转换这些东西?

最佳答案

和我一样的问题

但我创建了通用工具并在下面解析,

第 1 步:创建函数 toCamel & keysToCamel

toCamel(s: string) {
return s.replace(/([-_][a-z])/ig, ($1) => {
return $1.toUpperCase()
.replace('-', '')
.replace('_', '');
});
}

keysToCamel(o: any) {
if (o === Object(o) && !Array.isArray(o) && typeof o !== 'function') {
const n = {};
Object.keys(o)
.forEach((k) => {
n[this.toCamel(k)] = this.keysToCamel(o[k]);
});
return n;
} else if (Array.isArray(o)) {
return o.map((i) => {
return this.keysToCamel(i);
});
}
return o;
}

第 2 步:当 JSON 数据从后端响应时。

例子:

JSON(来自后端的响应)

{"user_id":"2014","full_name":"bamossza","token":"jwt","lang_id":"TH"}

界面

export interface Profile {
userId: number;
fullName: string;
token: string;
langId: string;
}

转换并映射到接口(interface)

this.profileService.callProfile(s.token)
.subscribe((response: Profile) => {
const profile = this.commonUtil.keysToCamel(response) as Profile;
console.log(profile.fullName); // bamossza
console.log(profile.langId); // TH
...
});

为我工作。

:为什么直到后端才转化???

A:因为我觉得 JSON "calmelCase""snake_case" 更难读。

尝试将该应用程序应用到您的项目中。

关于Angular/Typescript 在接口(interface)中从蛇形大小写转换为驼峰大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44437953/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com