angular - subscribe 方法中的代码没有按正确的顺序运行
问题描述
从获取请求我收到对象数组,我想将该数据分配给两个不同的变量。一个变量将获得所有数据,第二个变量将获得该数据的变异版本。
我试过的代码:
this.service.getEmployeeTimesheets().subscribe(res => {
this.timesheets = res;
this.mutatedTimesheets = res.map(j => {
delete j["keyName1"];
delete j["keyName2"];
});
console.log(this.mutatedTimesheets);
});
发生的事情是由于某种原因时间表值被更改并且 mutatedTimesheets 得到未定义的数组
解决方案
你犯了2个错误。
1)通过引用复制数组。所以时间表也得到修改
2)不从地图返回修改后的元素
试试这个
this.service.getEmployeeTimesheets().subscribe(res => {
this.timesheets = res;
this.mutatedTimesheets = res.map(j => {
// Re-reference the current object
j = {...j};
delete j["keyName1"];
delete j["keyName2"];
return j;
});
console.log(this.mutatedTimesheets);
});
推荐阅读
- mysql - 赫罗库。玛丽亚数据库。拒绝用户访问
- python - Python 检查列表均匀度
- spring - 如何在spring中编写while循环
- javascript - Socket.io 事件监听器在我的 React 类组件中自发触发,没有服务器输出
- excel - 将文件夹中的 Excel 文件复制到一个 Excel 文件中
- linux-kernel - 使用 binutils 2.31 或更高版本构建时设备无法启动
- python - 应该对原始数据还是拆分数据执行交叉验证分数?
- java - JAVA - 隐藏类 Selenium
- android - 从 sqlite 数据库中设置 recyclerview 中的数据时出现 IndexOutOfBound 异常
- c# - 使用表达式树创建自动映射器配置