我正在切换以使用新的 HttpClient Angular 。
正在调用的 API 以一种格式返回 json 数据。我想获取这些数据并将其转换为适合 UI 使用的 typescript 模型类。
我之前这样做的方法是使用 map 功能,例如
return this.httpClient.get(url, { headers: headers })
.map(mapFunction)
.catch(errorFunction);
map 函数执行转换 api 响应的繁重工作,引入模型对象,例如
const mapFunction =
(response: Response) => {
const data = response.json();
const contacts: Contact[] = [];
let i = 0;
for (const result of data.resourceResults) {
i = i + 1;
const contact: Contact = new Contact();
contact.role = result.r
对我来说,这似乎很麻烦,我基本上是在寻找一种方法来将对象从 api 响应类型映射到 ui 模型类型,而不必为每个请求使用自定义映射函数。
最佳答案
如果没有明确指定需要映射的内容,就无法进行自定义映射。要么你告诉服务器端返回一个 UI 友好的响应,要么你需要在客户端自己做映射。
如果你想在客户端映射响应,你可以利用 Typescript 类,并使用它的 constructor
快速生成你想要的项目:
export class Contact {
public name:string;
public roles:any;
constructor(name:string, roles: any) {
//specify your own constructor logic
this.name=name;
this.roles=roles
}
}
现在你可以写在你的
mapFunction
将响应显式转换为 Contact
的列表s。此外,您可以使用数组的 .map()
遍历对象,而无需编写 for 循环:public mapFunction = (response: Response) => {
const data = response.json();
const resource = data.resourceResults;
//map it
return resource.map(result => new Contact(result.n, result.r))
}
繁琐与否,我认为是主观的。但绝对可以以更优雅的方式编写代码。
关于angular - 处理将 API 对象映射到 UI 模型对象的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47632430/