Angular应用程序连接到REST Api。现在,例如,rest api使用User
对象响应,如下所示:
{
first_name: 'Super',
last_name: 'Admin'
}
在角度截面中,User
模型如下所示:
export class User {
firstName: string;
lastName: string;
constructor() {
}
}
现在,当我从服务获取数据时,我如何将响应对象映射到angular模型?由于名称不同(可能是更复杂的情况),firstName
将如何表示first_name
当请求参数为first_name
和last_name
时,向接口发送请求时也会出现这种情况。
它可以通过单独映射每个字段或创建UserForm对象来完成。但是有没有办法使用转换器,它可以将api字段映射到模型对象,反之亦然?
发布于 2018-07-15 16:32:31
好吧,我更喜欢在服务中添加propertyParamMap
对象,它将在发送任何请求到api之前或从Api接收到响应之后使用。
service.ts -发送接口请求的位置。
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]];
}
}
});
}
https://stackoverflow.com/questions/51346560
复制相似问题