angular - 在解构项目和解构行为后创建一个新数组
问题描述
我正在从服务返回一个 observable,我想创建一个新数组;
stackblitz代码在这里
allCodesAndIds: Option[] = [];
服务电话
getAllItems(): Observable<Item> {
return of(this.jsonData);
}
通过以下方式解构项目
getAllItems() {
const items$ = this.service.getAllItems();
items$.pipe().subscribe(res => {
const [id, code] = res.items;
console.log(id, code);
});
}
我希望我的allCodesAndIds
数组如下所示
[
{
id: 1,
descp: "item 1"
},
{
id: 2,
descp: "item 2"
},
{
id: 3,
descp: "item 3"
},
{
id: 4,
descp: "item 4"
},
{
id: 5,
descp: "item 5"
}
]
此外,当前的 console.log 仅打印 2 项
{id: 1, descp: "item 1", code: "code1"}
{id: 2, descp: "item 2", code: "code2"}
而我期待它返回所有 5 个项目。有人可以解释一下这背后的原因。请。
感谢您的时间和帮助!
解决方案
如果我理解正确,您想像这样解构您的项目:
const items = res.items.map(({id, descp}) => ({id, descp});
这被称为object destructuring
。
在您的代码段中,您没有使用对象解构,而是使用array destructuring
. 这会从您的项目列表中获取第一个和第二个项目。
const [item1, item2] = res.items;
数组解构也有它的用例,例如分离列表的头部和尾部,这对递归算法很有用:
const [first, ...rest] = res.items;
推荐阅读
- r - plotly::subplot 注释标题在 R Shiny 中消失
- javascript - 为什么 innerText 确实适用于不可见元素?它不应该
- javascript - 平面列表不滚动
- r - 从 Rmarkdown 中允许换行和转义 Markdown 和 Latex 命令的函数打印
- javascript - 如何使用 JQuery 更新卡路里计算器的总卡路里?
- python - 由于 EnviromentError 无法安装软件包 - Python
- javascript - 过滤一个集合数据值一个承诺
- amazon-aurora - wal_level < 升级极光 postgres db 时出现逻辑错误
- python - 如何使用 `PyQt5` 后端使来自`matplotlib` 的控制台消息静音?
- flutter - 如何创建具有与其父类构造函数不同的参数的自定义(ElevatedButton)类构造函数?