[英]Modify api response in service of angular
I am trying to modify the response return by API request. 我正在尝试通过API请求修改响应返回。 Right now I am getting the response as 现在我得到的答复是
[
{
name: "Afghanistan"
},
{
name: "Åland Islands"
}
]
I want to modify it to: 我想将其修改为:
[
{
name: "Afghanistan",
name1: "Afghanistan",
name2: "Afghanistan"
},
{
name: "Åland Islands",
name1: "Åland Islands",
name2: "Åland Islands"
}
]
I am trying to copy name field and create new fields eg: name1, name2 in same object . 我正在尝试复制名称字段并在同一对象中创建新字段,例如:name1,name2。 Here is working project https://stackblitz.com/edit/angular-8bzcdp can any one help 这是工作中的项目https://stackblitz.com/edit/angular-8bzcdp可以帮忙吗
You can change your method to: 您可以将方法更改为:
getRecords() {
return this.http.get('https://restcountries.eu/rest/v2/all').pipe(
map((res: any[]) => {
const data = res.map(obj => ({
name: obj.name,
name1: obj.name,
name2: obj.name
}));
return data;
})
);
}
Here on the resulting response array ( res[]
) we map each element into a json object based on your criteria and return the newly created json object. 在结果响应数组( res[]
)上,我们根据您的条件将每个元素映射到json对象,并返回新创建的json对象。
You can modify your response after you subscribe 订阅后即可修改回复
this.service.getRecords().subscribe(res => {
console.log(res);
console.log(res.reduce((a, c) => Object.assign(a, c), {}));
});
for details please visit the updated stackblitz link 有关详细信息,请访问更新的stackblitz链接
https://stackblitz.com/edit/angular-nwwef1?file=src/app/app.component.ts https://stackblitz.com/edit/angular-nwwef1?file=src/app/app.component.ts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.