首页 > 解决方案 > 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 得到未定义的数组

标签: angulartypescriptsubscribe

解决方案


你犯了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);

   });

推荐阅读