![](/img/trans.png)
[英]How to iterate a JSON array and add data from an async arrow function?
[英]How to async add data (needs to iterate twice) to API service in angular?
我有一个 json 文件,如下所示:
{
"users": [
{
"id": "person1",
"information": [
{
"first_name": "Mike",
"last_name": "Patty",
"address": ["address1","address2"]
},
{
"first_name": "Mike2",
"last_name": "Patty2",
"address": ["address1","address2"]
}
]
},
{
"id": "person2",
"information": [
{
"first_name": "Tom",
"last_name": "Jerry",
"address": ["address1","address2"]
},
{
"first_name": "Tom2",
"last_name": "Jerry2",
"address": ["address1","address2"]
}
]
}
]
}
我想迭代用户并将每个用户的信息添加到API数据库中。 addInfo
请求需要: first_name
, last_name
和address
( address
是数组)。 这是因为我需要保存信息请求的响应以供以后使用。 我对角度/打字稿很陌生。 所以这是我目前正在尝试编写的代码:
先感谢您!
forkjoin 需要一组 observables,执行 observables,并且当所有 onbservables 完成时返回每个的响应。 所以你应该创建这个 observables 数组。 为此,您将数组“用户”转换为调用数组 API。 为此,您使用“地图”(是“数组的地图”)
const addUsers$ = forkJoin(
User.map(x=>
//each "x" is in the way {id:..,information:{first_name:..,last_name:..,address:..}
this.APIservice.addInformation(
{
firstName: x.information.first_name,
lastName: x.information.last_name,
organizations: x.information.address
}
)).subscribe((res:any[])=>{
//in res[0] you has the response to the first call API,
//in res[1] you has the response to the second one
//...
})
试试flatMap
const addUsers$ = forkJoin(
Users.flatMap(user => user.information).map(info =>
this.APIservice.addInformation(
{
firstName: info.first_name,
lastName: info.last_name,
organizations: info.address
}
)))
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.