问题和我的一样。但是我创建了通用的工具并解决了以下问题,
步骤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;
}
转换并映射到接口
this.profileService.callProfile(s.token)
.subscribe((response: Profile) => {
const profile = this.commonUtil.keysToCamel(response) as Profile;
console.log(profile.fullName);
console.log(profile.langId);
...
});
为我工作。
Q: 为什么你不在后端进行转换?
A: 因为我觉得 JSON 中的"camelCase"比"snake_case"难以阅读。
尝试将此应用于您的项目中。