Angular应用程序连接到RESTApi。例如,rest api用User
对象响应,如:
{
first_name: 'Super',
last_name: 'Admin'
}
在Angular部分,User
模型如下:
export class User {
firstName: string;
lastName: string;
constructor() {
}
}
现在,当我从服务获取数据时,我如何将响应对象映射到角度模型?由于名称不同(情况可能更复杂(,firstName
将如何表示first_name
?
由于请求参数为first_name
和last_name
,因此向api发送请求也会出现这种情况。
这可以通过分别映射每个字段或创建UserForm对象来完成。但是,有没有任何方法可以使用transformer将api字段映射到模型对象,反之亦然?
好吧,我更喜欢在服务中添加propertyParamMap
对象,它将在向Api发送任何请求之前或从Api接收响应之后使用。
service.ts-发送api请求的位置。
class MyService{
private propertParamMap = {};
constructor() {
this.propertyParamMap = {
'id': 'id',
'firstName': 'first_name',
'lastName': 'last_name',
};
}
}
示例代码-可以更好地优化
post (data) {
// map before sending request
data = data.map((item) => this.propertyParamMap[item])
this.http.post(data).pipe(
map((resp) => {
// map after receiving response
let modelData = {}
for (let keyProperty in this.propertyParamMap) {
// loop through propertyParamMap array
if (this.propertyParamMap[keyProperty] in resp) {
// check if value exist within response object
modelData[keyProperty] = resp[this.propertyParamMap[keyProperty]];
}
}
});
}